Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- namespace ConsoleApplication2
- {
- class Program
- {
- static void Main(string[] args)
- {
- var sw = Stopwatch.StartNew();
- for (int i = 0; i < 10000000; i++)
- {
- var instance = LazySingleton.Instance;
- //var instance = DoubleCheckLockSingleton.Instance;
- }
- Console.WriteLine(sw.ElapsedMilliseconds);
- }
- }
- public class LazySingleton
- {
- private static readonly Lazy<LazySingleton> _instance
- = new Lazy<LazySingleton>(() => new LazySingleton(), isThreadSafe: true);
- private LazySingleton() {}
- public static LazySingleton Instance => _instance.Value;
- }
- public class DoubleCheckLockSingleton
- {
- private static readonly object SyncObj = new object();
- private static volatile DoubleCheckLockSingleton _instance = null;
- private DoubleCheckLockSingleton(){ }
- public static DoubleCheckLockSingleton Instance
- {
- get
- {
- if (_instance == null)
- {
- lock (SyncObj)
- {
- if (_instance == null)
- {
- _instance = new DoubleCheckLockSingleton();
- }
- }
- }
- return _instance;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement