Thread 内容多,不易控制。 Task 好用(必须掌握)。
1 #region Private Method 2 /// <summary> 3 /// 一个比较耗时耗资源的私有方法 4 /// </summary> 5 /// <param name="name"></param> 6 private void DoSomethingLong(string name) 7 { 8 Console.WriteLine($"****************DoSomethingLong Start {name} {Thread.CurrentThread.ManagedThreadId} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}***************"); 9 long lResult = 0; 10 for (int i = 0; i < 2000000000; i++) 11 { 12 lResult += i; 13 } 14 //Thread.Sleep(2000); 15 16 Console.WriteLine($"****************DoSomethingLong End {name} {Thread.CurrentThread.ManagedThreadId} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}***************"); 17 } 18 #endregion
声明:
1 Task task = Task.Factory.StartNew(() => this.DoSomethingLong(name));
WaitAny() && WaitAll()---卡主线程,卡界面
1 Console.WriteLine("before WaitAny"); 2 Task.WaitAny(taskList.ToArray());//当前线程等待某个任务的完成 主线程 3 Console.WriteLine("after WaitAny"); 4 5 6 Console.WriteLine("before WaitAll"); 7 Task.WaitAll(taskList.ToArray());//当前线程等待全部任务的完成 主线程 8 Console.WriteLine("after WaitAll");
ContinueWhenAny() && ContinueWhenAll() ---不卡主线程,不卡界面
1 taskList.Add(Task.Factory.ContinueWhenAny(taskList.ToArray(), t => 2 { 3 Console.WriteLine(t.IsCompleted); 4 Console.WriteLine($"ContinueWhenAny {Thread.CurrentThread.ManagedThreadId}"); 5 })); 6 7 taskList.Add(Task.Factory.ContinueWhenAll(taskList.ToArray(), tList => 8 { 9 Console.WriteLine(tList[0].IsCompleted); 10 Console.WriteLine($"ContinueWhenAll {Thread.CurrentThread.ManagedThreadId}"); 11 })); 12 //回调形式的,全部任务完成后执行的后续动作
ContinueWith() 建议少用(嵌套太多,容易晕)
1 //Task taskContinue = task.ContinueWith(t => 2 // { 3 // Console.WriteLine(t.IsCompleted); 4 // Console.WriteLine($"ContinueWhenAny {Thread.CurrentThread.ManagedThreadId}"); 5 // }).ContinueWith(t => 6 // { 7 // Console.WriteLine(t.IsCompleted); 8 // Console.WriteLine($"ContinueWhenAny {Thread.CurrentThread.ManagedThreadId}"); 9 // });