C# Events and Thread Safety

前端 未结 15 1342
甜味超标
甜味超标 2020-11-22 06:00

UPDATE

As of C# 6, the answer to this question is:

SomeEvent?.Invoke(this, e);

I frequently hear/read the fo

15条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 06:15

    for single threaded applicaitons, you are correc this is not an issue.

    However, if you are making a component that exposes events, there is no guarantee that a consumer of your component is not going to go multithreading, in which case you need to prepare for the worst.

    Using the empty delegate does solve the problem, but also causes a performance hit on every call to the event, and could possibly have GC implications.

    You are right that the consumer trie dto unsubscribe in order for this to happen, but if they made it past the temp copy, then consider the message already in transit.

    If you don't use the temporary variable, and don't use the empty delegate, and someone unsubscribes, you get a null reference exception, which is fatal, so I think the cost is worth it.

提交回复
热议问题