Are C# delegates thread-safe?

前端 未结 4 1145
甜味超标
甜味超标 2020-12-14 01:34

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 i

4条回答
  •  忘掉有多难
    2020-12-14 02:11

    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.

提交回复
热议问题