Is a readonly field in C# thread safe?

后端 未结 3 1232
小蘑菇
小蘑菇 2020-12-17 08:59

Is a readonly field in C# thread safe?

public class Foo
{
  private readonly int _someField;

  public Foo()
  {
    _someField = 0;
  }

  publ         


        
相关标签:
3条回答
  • 2020-12-17 09:14

    Not looking at your example but in general it depends what is readonly applied to, for example if dictionary is declared readonly you can still update keyvalue pairs

    0 讨论(0)
  • 2020-12-17 09:20

    Yes - your code doesn't expose this within either constructor, so no other code can "see" the object before it's been fully constructed. The .NET memory model (as of .NET 2) includes a write barrier at the end of every constructor (IIRC - search Joe Duffy's blog posts for more details) so there's no risk of another thread seeing a "stale" value, as far as I'm aware.

    I'd personally still usually use a property instead, as a way of separating implementation from API, but from a thread-safety point of view it's fine.

    0 讨论(0)
  • 2020-12-17 09:25

    That depends what's in the field.

    Reading from a readonly field, or from any field that is smaller than the word length (including all reference types) is an atomic operation.

    However, the object inside the readonly field may or may not be thread-safe.

    0 讨论(0)
提交回复
热议问题