Is it always safe to unsubscribe from an event inside a handler?

Suppose I have this (incomplete) class in which I create an event without first assigning it to a variable to make it thread safe:

public class Test { public event EventHandler SomeEvent; void OnSomeEvent(EventArgs e) { if (SomeEvent != null) SomeEvent(this, e); } } 

Would it be possible to unsubscribe from the event handler from myself or would there be a problem similar to what would happen when deleting items from the collection during enumeration?

 void SomeEventHandler(object sender, EventArgs e) { testInstance.SomeEvent -= SomeEventHandler; } 
+8
c # events
source share
2 answers

To clarify a little different answer:

Events are based on delegates (in almost all cases). Delegates are immutable. This also applies to multicast delegates.

When the event is called, the delegate is loaded and then called. If the field in which the delegate is stored is changed, this does not affect the delegate already loaded.

Therefore, it is safe to modify the event from the handler. These changes will not affect the current call. This is guaranteed.

All this applies only to events supported by the delegate. C # and the CLR support custom events that can do anything at all.

+5
source share

It would be safe, however, just to know that this is not a guarantee that the code in SomeEventHandler will be executed only once. A race condition may occur if you have a multi-threaded code.

Edit : Unsubscribing from an event, behind the scenes, brings together delegates to create a list of delegates. (Detailed information can be found on this article by John Skeet, the man himself )

Note that the event uses locks to ensure thread safety in conjunction with a delegate. After combining the delegate with your event, you will receive a list of delegates. However, when you raise an event, it is not guaranteed that the latest version of the combined delegates will be used. (see Thread-safe events), but this is not due to the fact that the event was disabled from within the event.

I hope my editing will give enough explanation :)

+4
source share

All Articles