views:

86

answers:

2

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.

A: 

I've got only vague knowledge of VB.NET, but what about AddHandler / RemoveHandler?

Bolek Tekielski
AddHandler/RemoveHandler is the VB.NET equivalent of += and -= in C#. Since I don't know every subscriber (unless I make the event custom) I can't RemoveHandler each one.
Julien Lebosquain
+3  A: 

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.

MarkJ
Thanks! Didn't see that documentation section, very helpful. As using reflection, that's seem quite heavy just to set some variables to null; but quite useful to assert at debug time that every field was correctly set to null.
Julien Lebosquain
I was thinking maybe there could be a general purpose method ClearAllSubscriptions that uses reflection to deal with any type: then all you need in your Clear method is `ClearAllSubscriptions Me`
MarkJ