How can a readonly static field be null?

后端 未结 5 851
误落风尘
误落风尘 2020-12-30 21:37

So here\'s an excerpt from one of my classes:

    [ThreadStatic]
    readonly static private AccountManager _instance = new AccountManager();

    private Ac         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 22:12

    This is a confusing part of the ThreadStatic attribute. Even though it creates a value per thread, the initalization code is only run on one of the threads. All of the other threads which access this value will get the default for that type instead of the result of the initialization code.

    Instead of value initialization, wrap it in a property that does the initialization for you.

    [ThreadStatic]
    readonly static private AccountManager _instance;
    
    private AccountManager()
    {
    }
    
    static public AccountManager Instance
    {
      get 
      { 
        if ( _instance == null ) _instance = new AccountManager();
        return _instance; 
      }
    }
    

    Because the value _instance is unique per thread, no locking is necessary in the property and it can be treated like any other lazily initialized value.

提交回复
热议问题