Are C# delegates thread-safe?

來源:互聯網
上載者: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 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 peskyNullReferenceException.

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(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.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.