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

In C #, I'm used to clearing every subscription to my user events in Dispose()to avoid memory leaks for subscribers forgetting to unsubscribe from my events.

This was very simple to do, just by calling MyEvent = null, as the C # compiler automatically generates a delegate field. Unfortunately, in VB.NET, there seems to be no easy way to do this. The only solution I came across was writing Custom Event, adding custom add and remove handlers that call Delegate.Combine/ Delegate.Remove, mainly what the C # compiler does. But doing it for every event, just to clear my subscriptions, seems a bit "redundant" to me.

Does anyone have any other idea to solve this problem? Thanks.

+3
source share
2 answers

This is exactly the same in VB.Net. The compiler automatically creates a delegate field for each event, like the C # compiler, but in VB this field is hidden. However, you can access the variable from your code - it is always called XXXEvent, where XXX is the name of the event.

This way you can easily clear the event subscription, as 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 also think it should be possible to use reflection to automatically find all hidden delegate variables and clear them. Then they do not need to be specified in the method Clear.

+5
source

VB.NET, AddHandler/RemoveHandler?

0

Source: https://habr.com/ru/post/1722426/


All Articles