Are C# auto-implemented static properties thread-safe?

廉价感情. 提交于 2019-11-27 22:45:59

It appears not. This is the decompilation with Reflector:

private static string Test
{
    [CompilerGenerated]
    get
    {
        return <Test>k__BackingField;
    }
    [CompilerGenerated]
    set
    {
        <Test>k__BackingField = value;
    }
}

Section 10.7.4 of the C# specification states:

When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backing field. The following example:

public class Point {
  public int X { get; set; } // automatically implemented
  public int Y { get; set; } // automatically implemented
}

is equivalent to the following declaration:

public class Point {
  private int x;
  private int y;
  public int X { get { return x; } set { x = value; } }
  public int Y { get { return y; } set { y = value; } }
}

That's what we promise, and that's what you get. The point of auto properties is to do the most basic, simple, cheap thing; if you want to do something fancier then you should write a "real" property.

No. You must wrap them in thread-locking mechanisms.

object _lock = new object();
public static Main(string[] args)
{
    lock(_lock)
    {
         Prop = new T();
    }


    T val = null;
    lock(_lock)
    {
         val = Prop;
    }
}

I don't believe so. I believe they are just syntatic sugar for:

private static T _prop;
public static T Prop
{
    get { return _prop; }
    set { _prop = value; }
}

There is no synchronization provided with automatic properties, including static properties.

If you need full thread safety, you'll want to use your own properties with a backing field, and handle the synchronization yourself.

For completeness, field-like events do have thread-safety built in, but they are alone in this. Automatically implemented properties do not have any such features. You can, however, do something like:

public static double SomeProp
{   // ### NOT RECOMMENDED ###
    [MethodImpl(MethodImplOptions.Synchronized)] get;
    [MethodImpl(MethodImplOptions.Synchronized)] set;
}

The problem with this is that it will lock the Type, which is a bad thing. I would implement my own synchronization for this, personally.

No, they not threadsafe. Static properties just as vulnerable as static fields are to concurrency issues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!