Reputation: 1065
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:
Upvotes: 3
Views: 54
Reputation: 3880
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.
Upvotes: 2