Is there any way to clear subscription to an event in VB.NET?
In C#, I took the habit on clearing every subscriptions to my custom events in Dispose()
to avoid memory leaks of subscribers forgetting to unsubscribe from my events.
It was very simple to do, simply by calling MyEvent = null
since the C# compiler automatically generates a delegate field. Unfortunately in VB.NET, there seems to be no simple way to do this. The only solution I came up with was to write a Custom Event
, adding custom add and remove handlers calling Delegate开发者_如何学编程.Combine
/ Delegate.Remove
, basically what the C# compiler does. But having to do this for every event just to be able to clear the subscriptions seems a little 'overkill' to me.
Does anyone have another idea to solve this problem? Thanks.
It's exactly the same in VB.Net. The compiler automatically creates a delegate field for each event, just like the C# compiler, but in VB the field is hidden. However you can access the variable from your code - it's always named XXXEvent, where XXX is the event name.
So you can easily clear subscriptions to the event, just like in C#:
Public Class Class1
Implements IDisposable
Event MyEvent()
Sub Clear() Implements IDisposable.Dispose
Me.MyEventEvent = Nothing ' clear the hidden variable '
End Sub
End Class
I'm also thinking it should be possible to use reflection to automatically find all the hidden delegate variables, and clear them. Then they don't have to be listed in the Clear
method.
I've got only vague knowledge of VB.NET, but what about AddHandler / RemoveHandler?
精彩评论