Reputation: 187
I read the C# Events and Thread Safety and the section Thread-safe delegate invocation in MSDN
Before asking quesion, i define thread safety, there are three aspects:
Let's look at this example again:
PropertyChanged?.Invoke(…)
var handler = this.PropertyChanged;
if (handler != null)
{
handler(…);
}
OK, in C# the R/W OP of reference type is no bad data problem. So, when invoke handler, it is never null. But, i still have questions
【Additional】
Yes,i cannot define the meaning of thread safety.I only want to give a NAME to item1-item3. And my the other doubt comes from the following field-like events are implemented using Interlocked.CompareExchange
What is this thing you call thread-safe? The code we’ve got so far is “thread-safe” in that it doesn’t matter what other threads do – you won’t get a NullReferenceException from the above code. However, if other threads are subscribing to the event or unsubscribing from it, you might not see the most recent changes for the normal reasons of memory models being complicated.
As of C# 4, field-like events are implemented using Interlocked.CompareExchange, so we can just use a corresponding Interlocked.CompareExchange call to make sure we get the most recent value. There’s nothing new about being able to do that, admittedly, but it does mean we can just write
CLEAN EVENT HANDLER INVOCATION WITH C# 6
Upvotes: 0
Views: 128
Reputation: 62093
You need to understand one thing about thread safety. Well, a couple of:
So, no, there is no magic mechanism that guarantees something that IS NOT GUARANTEED PER DOCUMENTATION because it would mean the cost would have to be paid every time, mostly also when not needed.
Event mechanisms in .NET are single threaded. Period. Live with it. They go back to a notification mechanism in the UI, and there, for rules likely older than you (i.e. they go back to times of ActiveX UI elements, which incidentally still exist in i.e. the standard file dialog) this is the domain of "anything in the UI is only ever changed by the ONE ui thread".
Upvotes: 1