简体   繁体   English

我应该在Reactive Extensions(Rx)Subject <T>上调用Dispose

[英]Should I be calling Dispose on Reactive Extensions (Rx) Subject<T>

I am using the Reactive Extensions (Rx) Subject as a direct replacement for C# events like so: 我使用Reactive Extensions(Rx)Subject作为C#事件的直接替代品,如下所示:

public class MyClass
{
    private Subject<string> subject;

    public IObservable<string> WhenSomethingHappened
    {
        get { return this.subject.AsObservable(); }
    }

    private void OnSomethingHappened(string something)
    {
        this.subject.OnNext(something);
    }
}

Note that I never call OnCompleted on my subject. 请注意,我从未在我的主题上调用OnCompleted。 Should MyClass be implementing IDisposable and calling this.subject.Dispose? MyClass应该实现IDisposable并调用this.subject.Dispose吗? This would mean that any implementation using Subject should implement IDisposable. 这意味着使用Subject的任何实现都应该实现IDisposable。

The reason I ask is that the IDisposable pattern is a bit like a disease, if one thing implements it, everything that uses it has to implement it too. 我问的原因是IDisposable模式有点像疾病,如果有一件事实现它,使用它的一切都必须实现它。

Nope, you don't really need to do this. 不,你真的不需要这样做。 When worrying about memory usage and lifetimes, think about disposing Subscriptions , not Subjects. 在担心内存使用和生命周期时,请考虑处理订阅 ,而不是主题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM