Is event subscription/unsubscription thread-safe?
-
My understanding of event handling in .net is that event subscription and unsubscription are performed by
m_theEvent[delegate].Combine(m_theEvent, subscribingDelegate)
orm_theEvent[delegate].Remove(m_theEvent, unsubscribingDelegate)
. Certainly that is how they are illustrated in the books I've read. Such constructs would not be threadsafe, but when I've written some code to bash events (I only have a single-processor) I've not seen any subscription failures though I have seen unsubscription failures. Do .net 2.0 and above do anything to ensure that subscriptions actually succeed (e.g. via locks or a CompareExchange loop), or is the code just getting "lucky", or what? If multiple threads will be subscribing and unsubscribing, may events safely be used or should some other mechanism be used instead? -
My understanding of event handling in .net is that event subscription and unsubscription are performed by
m_theEvent[delegate].Combine(m_theEvent, subscribingDelegate)
orm_theEvent[delegate].Remove(m_theEvent, unsubscribingDelegate)
. Certainly that is how they are illustrated in the books I've read. Such constructs would not be threadsafe, but when I've written some code to bash events (I only have a single-processor) I've not seen any subscription failures though I have seen unsubscription failures. Do .net 2.0 and above do anything to ensure that subscriptions actually succeed (e.g. via locks or a CompareExchange loop), or is the code just getting "lucky", or what? If multiple threads will be subscribing and unsubscribing, may events safely be used or should some other mechanism be used instead?This might help: Event Declaration Syntax[^]
Giorgi Dalakishvili #region signature my articles #endregion
-
This might help: Event Declaration Syntax[^]
Giorgi Dalakishvili #region signature my articles #endregion
I'm using vb.net, rather than c#, but I think I understand most of the article. A few things I'm not quite clear on, though: -1- If I declare a custom event, will all subscribers to the event use the subscribe/unsubscribe methods described therefor, and make no other access to anything to do with the event? -2- What happens to event handlers for an object that falls out of scope? If I have an object that contains a reference to another object that sends events, will the presence of the former object in the latter object's subscription list keep it alive indefinitely? -3- Is there any way to have an event subscriber keep or pass something other than a raw delegate? My guess is probably not when using the standard mechanisms, but if a subscriber could hold some data which could be passed with an unsubscribe request, efficient lock-free thread-safe subscription management would be practical.