Are C# delegates thread-safe?

2019-01-22 07:50发布

问题:

If you have a class instance with a delegate member variable and multiple threads invoke that delegate (assume it points to a long-running method), is there any contention issues?

Do you need to lock around the delegate or is it safe for each thread to call the method the delegate points to, since each thread gets it's own call stack?

回答1:

Regarding the invocation of the delegate the answer is yes.

Invoking a delegate is thread-safe because delegates are immutable. However, you must make sure that a delegate exists first. This check may require some synchronization mechanisms depending on the level of safety desired.

For example, the following could throw a NullReferenceException if SomeDelegate were set to null by another thread between the null check and the invocation.

if (SomeDelegate != null)
{    
  SomeDelegate();
}

The following is a little more safe. Here we are exploiting the fact that delegates are immutable. Even if another thread modifies SomeDelegate the code is harded to prevent that pesky NullReferenceException.

Action local = SomeDelegate;
if (local != null)
{
  local();
}

However, this might result in the delegate never being executed if SomeDelegate was assigned a non-null value in another thread. This has to do with a subtle memory barrier problem. The following is the safest method.

Action local = Interlocked.CompareExchange(ref SomeDelegate, null, null);
if (local != null)
{
  local();  
}

Regarding the execution of the method referenced by the delegate the answer is no.

You will have to provide your own thread-safety guarentees via the use of synchronization mechanisms. This is because the CLR does not automatically provide thread-safety guarentees for the execution of delegates. It might be the case that the method does not require any further synchronization to make it safe especially if it never access shared state. However, if the method reads or writes from a shared variable then you will have to consider how to guard against concurrent access from multiple threads.



回答2:

No they are not thread-safe and yes you'll have to manage concurrency yourself.



回答3:

Directly from the documentation of MulticastDelegate:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

The Delegate class contains the same information, so there you have it.



回答4:

Modifying an event is not thread-safe, but invoking a delegate is. Since a delegate is immutable, it is thread-safe. See remarks here MSDN Delegate class:

Borrowed from here: In CLR Via C# Richter points out a few subtle points about event invocation in multi-threaded classes:

A delegate chain is immutable; a new chain is created to replace the first. A delegate chain with zero subscribers is null. That means (if your event is public) it may transition from null to non-null and vice versa, at any time.