"c# is it thread safe to subscribe same event handler for all objects" Code Answer

5

thread-safety always needs a context - a from what.

if you mean the +=

for the +=, that depends on how the event is implemented. if it is implemented as a field-like event, i.e.

public event someeventtype eventreceived;

then yes: it is thread-safe. the specification requires that the accessors for field-like events are thread-safe, although the implementation can vary (for example, the ms compiler used to use lock(this) or lock(typeof(declaringtype)), however it now uses interlocked instead).

if the event is implemented manually, i.e.

public event someeventtype eventreceived {
    add { ... }
    remove { ... }
}

then the thread-safety is defined entirely by the add/remove implementations.

if you mean the invoke

then that is thread-safe since delegates are immutable, but note that it all happens on the single thread that invokes the thread. however, a common mistake is to introduce a race condition in a null test:

if(eventreceived != null) eventreceived(this, someargs);

the above is not thread-safe, since technically the value of eventreceived can change after the test. to ensure this does not error, it should be:

var handler = eventreceived;
if(handler != null) handler(this, someargs);

if you mean the handlers

then the thread-safety is defined entirely by the individual handlers. for example, in ui applications it is the handlers that must check for, and switch to, the ui thread.

By dangermouse on September 1 2022

Answers related to “c# is it thread safe to subscribe same event handler for all objects”

Only authorized users can answer the Search term. Please sign in first, or register a free account.