当对象处置时,请从事件中取消订阅
我要弄清楚的是如何声明对象引用在将订阅处置为
异常设置为异常。处置订阅之前,对象被处置。 这是一个简化的示例:fromeventPattern
时,在观察到的fromeventPattern
时,将
void Main()
{
EventSource oEventSource = new();
var source = Observable.FromEventPattern<MyEventArgs>(
h => oEventSource.MyEvent += h,
h => {
//if (oEventSource != null)
oEventSource.MyEvent -= h; // <--- error thrown here
})
.Select(x => x.EventArgs.Value)
.Subscribe(x => Console.WriteLine(x));
Observable.Interval(TimeSpan.FromMilliseconds(500)).Subscribe(x =>
{
oEventSource?.RaiseMyEvent(x);
});
Thread.Sleep(3000);
oEventSource = null;
Thread.Sleep(2000);
source.Dispose(); // <--- error thrown when disposing subscription
}
public class EventSource
{
public event EventHandler<MyEventArgs> MyEvent;
public void RaiseMyEvent(long x){
MyEvent?.Invoke(this, new MyEventArgs(x));
}
}
public class MyEventArgs : EventArgs
{
public MyEventArgs(long x) { Value = x;}
public long Value { get; set; }
}
我无法确保在处理“ Eventsource”对象之前处置订阅,因为该对象是在ViewModel中定义的,并且与订阅发生的视图绑定在一起。
在删除处理程序之前检查Eventsource对象是否存在停止升高的错误(if(oeventsource!= null)
),但是由于处理程序从未被删除,它不会引入内存泄漏吗?
What I'm trying to figure out is how to declaratively avoid the Object reference not set to an instance of an object
exception thrown when disposing of subscription to FromEventPattern
observable when the observed object gets disposed of before disposing of the subscription.
Here's a simplified example:
void Main()
{
EventSource oEventSource = new();
var source = Observable.FromEventPattern<MyEventArgs>(
h => oEventSource.MyEvent += h,
h => {
//if (oEventSource != null)
oEventSource.MyEvent -= h; // <--- error thrown here
})
.Select(x => x.EventArgs.Value)
.Subscribe(x => Console.WriteLine(x));
Observable.Interval(TimeSpan.FromMilliseconds(500)).Subscribe(x =>
{
oEventSource?.RaiseMyEvent(x);
});
Thread.Sleep(3000);
oEventSource = null;
Thread.Sleep(2000);
source.Dispose(); // <--- error thrown when disposing subscription
}
public class EventSource
{
public event EventHandler<MyEventArgs> MyEvent;
public void RaiseMyEvent(long x){
MyEvent?.Invoke(this, new MyEventArgs(x));
}
}
public class MyEventArgs : EventArgs
{
public MyEventArgs(long x) { Value = x;}
public long Value { get; set; }
}
I cannot make sure the subscription is disposed of before disposing of the "EventSource" object because the object is defined in viewModel and it is bound to the View where the subscription takes place.
Checking if EventSource object exists before removing the handler stops the error being raised (if (oEventSource != null)
), but won't it introduce a memory leak since the handler is never removed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的逻辑有很多混乱,您的样式并没有真正使用RX EG序列合成性。但是,对您的问题的答案是简单地订阅您的来源Uppon您想要的条件
there is much confusion to your logic and your style is not really using RX e.g sequence composability. However an answer to your question is simply unsubscribe your source uppon the condition you want