Add delegate to event - thread safety

后端 未结 3 1818
南笙
南笙 2020-11-30 07:43

It is possible to execute the following code from multiple threads simultaneously.

this._sequencer.Completed += OnActivityFinished;

Is it t

3条回答
  •  迷失自我
    2020-11-30 07:58

    for field-like events adding/removing of handlers is thread-safe. From spec:

    When compiling a field-like event, the compiler automatically creates storage to hold the delegate, and creates accessors for the event that add or remove event handlers to the delegate field. In order to be thread-safe, the addition or removal operations are done while holding the lock (§8.12) on the containing object for an instance event, or the type object (§7.6.10.6) for a static event.

    However it is true for C# 3.0 and lesser, in C# 4.0 compiler generates lock-free implementation using Interlocked routines (but spec remains the same - bug?)

    In custom implementations no one can tell exactly... except maybe the author of code :)

提交回复
热议问题