Using IDisposable to unsubscribe events

前端 未结 9 2116
广开言路
广开言路 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:44

    One thing that bothers me about using IDisposable pattern for unsubscribe from events is Finalization issue.

    Dispose() function in IDisposable is supposed to be called by the developer, HOWEVER, if it isn't called by the developer, it is a understood that the GC will call this function (by the standard IDisposable pattern, at least). In your case, however, if you don't call Dispose no one else will - The event remains and the strong reference holds GC from calling the finalizer.

    The mere fact that Dispose() won't be called automatically by GC seems to me enough to not to use IDisposable in this case. Perhaps it calls for a new application specific interface that says that this type of object must have a Cleanup function called to be disposed by GC.

提交回复
热议问题