Search code examples
c#atomic

Atomically figuring out if a handler has subscribers


Right now, I am using the Interlocked.CompareExchange method in order to check if we are on the right thread, as well as if there are any subscribers to an event handler. If both of these conditions are true, the event will be fired off. I do this with the following code:

Interlocked.CompareExchange(ref MyEventHandler, null, null)?.Invoke(this, MyArguments);

This works pretty nicely for me. However, here is what I would like to know. Is there any way to refactor this statement so that I can return a boolean, indicating whether or not there were any subscribers to the MyEventHandler?

-- Edit --

I would also like to keep the same functionality of firing the event (if the conditions are satisfied) along with being able to know whether or not there were any subscribers to the handler.

-- Edit 2 --

Re-reading this myself, I think it could be worded a little better. Here is what I am trying to do:

  1. Check if we are on the right thread.
  2. Check for subscribers.
  3. Fire the event if conditions 1 and 2 are satisfied.
  4. Assign a boolean as true if there were subscribers, false if there were not

Solution

  • var handler = Interlocked.CompareExchange(ref MyEventHandler, null, null);
    var hasSubscribersAndOnRightThread = handler != null &&
        handler.GetInvocationList().Any(h => h != null) && AmIOnTheRightThread();
    
    if (hasSubscribersAndOnRightThread) handler.Invoke(this, MyArguments);
    

    I don't see any race conditions here that require more than that.