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:
- (item1)no bad data R/W. (intermediate data)
- (item2)no effect of instruction reoder.
- (item3)no effect of cache consistency.
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
- Is there a mechanism at the bottom of C# to ensure that an interlocked API operation is actually applied to the PropertyChanged, so there will be no problems with instruction reorder and cache consistency.
- If there is indeed a similar interlocked mechanism, is it only for delegate and event types? Is there such a guarantee for other variables type that can use .? operator.
【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