Are C # delegates thread-safe?

Source: Internet
Author: User

Http://stackoverflow.com/questions/6349125/are-c-sharp-delegates-thread-safe

 

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 mechanic ISMs depending on the level of safety desired.

For example, the following cocould throwNullreferenceexceptionIfSomedelegateWere 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 modifiesSomedelegateThe code is harded to prevent that peskyNullreferenceexception.

ActionLocal=Somedelegate;If(Local! =Null){Local();}

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

ActionLocal=Interlocked.Compareexchange(RefSomedelegate,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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.