Are static variables thread-safe? C#

后端 未结 7 1631
南笙
南笙 2020-12-03 00:35

I want to create a class which stores DataTables, this will prevent my application to import a list of details each time I want to retrieve it. Therefore this should be done

7条回答
  •  我在风中等你
    2020-12-03 01:23

    I thought it would be worth adding that Double Check Locking has since been implemented in .net framework 4.0 in a class named Lazy. So if you would like your class to include the locking by default then you can use it like this:

    public class MySingleton
    {
        private static readonly Lazy _mySingleton = new Lazy(() => new MySingleton());
    
        private MySingleton() { }
    
        public static MySingleton Instance
        {
            get
            {
                return _mySingleton.Value;
            }
        }
    }
    

提交回复
热议问题