开发者

Is there any way to clear subscription to an event in VB.NET?

开发者 https://www.devze.com 2022-12-11 04:27 出处:网络
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.

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消