namespace TestThread { internal class Program { static int count = 0; static object locker = new object(); static void Main(string[] args) { List<Task> tasks = new List<Task>(); for (int i = 0; i < 10; i++) { var tempIx = i; var task = new TaskFactory().StartNew(async () => { Console.WriteLine("线程开始" + tempIx); Monitor.Enter(locker); await AddOne(); Monitor.Exit(locker); Console.WriteLine("线程结束" + tempIx); }); tasks.Add(task); } // Task.WhenAll(tasks.ToArray()); Task.WaitAll(tasks.ToArray()); Console.WriteLine("result:" + count); Console.ReadLine(); } static async Task AddOne() { for (int i = 0; i < 10000; i++) { // lock (locker) { count++; } } } } }
标签:tasks,Console,int,await,locker,static,WriteLine,等待 From: https://www.cnblogs.com/chinasoft/p/17220449.html