static async Task ProcessAsync() { var unsafeState = new UnsafeState(); Task[] tasks = new Task[4]; for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(unsafeState)); } await Task.WhenAll(tasks); WriteLine("---------------------------------------"); var firstState = new DoubleCheckedLocking(); for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(firstState)); } await Task.WhenAll(tasks); WriteLine("---------------------------------------"); var secondState = new BCLDoubleChecked(); for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(secondState)); } await Task.WhenAll(tasks); WriteLine("---------------------------------------"); var lazy = new Lazy <ValueToAccess>(Compute); var thirdState = new LazyWrapper(lazy); for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(thirdState)); } await Task.WhenAll(tasks); WriteLine("---------------------------------------"); var fourthState = new BCLThreadSafeFactory(); for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(fourthState)); } await Task.WhenAll(tasks); WriteLine("---------------------------------------"); }
static async Task ProcessAsynchronously() { // 不安全的对象,构造方法会被调用了多次, // 并且不同的线程中值是不同的 var unsafeState = new UnsafeState(); Task[] tasks = new Task[4]; for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(unsafeState)); } await Task.WhenAll(tasks); Console.WriteLine("------------------------------"); // 使用双重锁定模式 var firstState = new DoubleCheckedLocking(); for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(firstState)); } await Task.WhenAll(tasks); Console.WriteLine("------------------------------"); // 使用LazyInitializer.EnsureInitialized方法 var secondState = new BCLDoubleChecked(); for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(secondState)); } await Task.WhenAll(tasks); Console.WriteLine("------------------------------"); // 使用Lazy<T>类型 var lazy = new Lazy <ValueToAccess>(Compute); var thirdState = new LazyWrapper(lazy); for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(thirdState)); } await Task.WhenAll(tasks); Console.WriteLine("------------------------------"); // 使用LazyInitializer.EnsureInitialized方法的一个不使用锁的重载 var fourthState = new BCLThreadSafeFactory(); for (int i = 0; i < 4; i++) { tasks[i] = Task.Run(() => Worker(fourthState)); } await Task.WhenAll(tasks); Console.WriteLine("------------------------------"); }