Using IDisposable to unsubscribe events

前端 未结 9 2080
广开言路
广开言路 2020-11-28 05:52

I have a class that handles events from a WinForms control. Based on what the user is doing, I am deferencing one instance of the class and creating a new one to handle the

相关标签:
9条回答
  • 2020-11-28 06:47

    Another option would be to use weak delegates or something like WPFs weak events, instead of having to unsubscribe explicitly.

    P.S. [OT] I consider the decision to only provide strong delegates the single most expensive design mistake of the .NET platform.

    0 讨论(0)
  • 2020-11-28 06:49

    My personal vote would be to have an Unsubscribe method in order to remove the class from events. IDisposable is a pattern intended for deterministic release of unmanaged resources. In this case you not managing any unmanaged resources and therefore should not be implementing IDisposable.

    IDisposable can be used to manage event subscriptions but probably shouldn't. For an example I point you to WPF. This is a library rife with events and event handlers. Yet virtually no class in WPF implements IDisposable. I would take that as an indication that events should be managed another way.

    0 讨论(0)
  • 2020-11-28 06:51

    No, you're not preventing the intention of IDisposable. IDisposable is intended as an all-purpose way to ensure that when you're done using an object, you can proactively clean up everything tied to that object. It doesn't have to be only unmanaged resources, it can include managed resources too. And an event subscription is just another managed resource!

    A similar scenario that frequently arises in practice is that you will implement IDisposable on your type, purely in order to ensure you can call Dispose() on another managed object. This is not a perversion either, it is just tidy resource management!

    0 讨论(0)
提交回复
热议问题