C# Events and Thread Safety

前端 未结 15 1153
甜味超标
甜味超标 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:03

    "Why is explicit-null-check the 'standard pattern'?"

    I suspect the reason for this might be that the null-check is more performant.

    If you always subscribe an empty delegate to your events when they are created, there will be some overheads:

    • Cost of constructing the empty delegate.
    • Cost of constructing a delegate chain to contain it.
    • Cost of invoking the pointless delegate every single time the event is raised.

    (Note that UI controls often have a large number of events, most of which are never subscribed to. Having to create a dummy subscriber to each event and then invoke it would likely be a significant performance hit.)

    I did some cursory performance testing to see the impact of the subscribe-empty-delegate approach, and here are my results:

    Executing 50000000 iterations . . .
    OnNonThreadSafeEvent took:      432ms
    OnClassicNullCheckedEvent took: 490ms
    OnPreInitializedEvent took:     614ms <--
    Subscribing an empty delegate to each event . . .
    Executing 50000000 iterations . . .
    OnNonThreadSafeEvent took:      674ms
    OnClassicNullCheckedEvent took: 674ms
    OnPreInitializedEvent took:     2041ms <--
    Subscribing another empty delegate to each event . . .
    Executing 50000000 iterations . . .
    OnNonThreadSafeEvent took:      2011ms
    OnClassicNullCheckedEvent took: 2061ms
    OnPreInitializedEvent took:     2246ms <--
    Done
    

    Note that for the case of zero or one subscribers (common for UI controls, where events are plentiful), the event pre-initialised with an empty delegate is notably slower (over 50 million iterations...)

    For more information and source code, visit this blog post on .NET Event invocation thread safety that I published just the day before this question was asked (!)

    (My test set-up may be flawed so feel free to download the source code and inspect it yourself. Any feedback is much appreciated.)

提交回复
热议问题