Can method inlining optimization cause race conditions?

后端 未结 3 915
感动是毒
感动是毒 2020-12-30 04:19

As seen in this question: Raising C# events with an extension method - is it bad?

I\'m thinking of using this extension method to safely raise an event:



        
3条回答
  •  执笔经年
    2020-12-30 04:51

    This is a memory model issue.

    Basically the question is: if my code contains only one logical read, may the optimizer introduce another read?

    Surprisingly, the answer is: maybe

    In the CLR specification, nothing prevents optimizers from doing this. The optimization doesn't break single-threaded semantics, and memory access patterns are only guaranteed to be preserved for volatile fields (and even that's a simplication that's not 100% true).

    Thus, no matter whether you use a local variable or a parameter, the code is not thread-safe.

    However, the Microsoft .NET framework documents a different memory model. In that model, the optimizer is not allowed to introduce reads, and your code is safe (independent of the inlining optimization).

    That said, using [MethodImplOptions] seems like a strange hack, as preventing the optimizer from introducing reads is only a side effect of not inlining. I'd use a volatile field or Thread.VolatileRead instead.

提交回复
热议问题