TPL Part 4,tplpart
簡單的Continuation
Task.ContinueWith(Task): 當指定的Task執行完畢時。
void Main(){Task rootTask = new Task(()=>{Console.WriteLine("root task completed");});root Task.ContinueWith((Task previousTask)=>{Console.WriteLine("continute task completed");}); rootTask.Start(); // waitfor input before exitingConsole.WriteLine("Press enter to finish");Console.ReadLine(); }
Task.ContinueWhenAll(Task[]):當指定的所有Task都執行完畢時,範例程式碼:
Task continuation = Task.Factory.ContinueWhenAll<int>(tasks, antecedents =>{foreach(Task<int> t in antecedents) {// dosomething}});
TaskFactory.ContinueWhenAny(Task[]):當指定的所有Task的任意1個執行完畢時,代碼與ContinueWhenAll類似(以下代碼中,列印出前1個Task的執行時間):
Task continuation = Task.Factory.ContinueWhenAny<int>(tasks,(Task<int>antecedent) => {//write out a message using the antecedent resultConsole.WriteLine("The first task slept for {0} milliseconds",antecedent.Result);});
Continue 選項
OnlyOnRanToCompletion僅當執行完
NotOnRanToCompletion:沒有執行完(被取消或出現異常)
OnlyOnFaulted:僅當出現異常
NotOnFaulted:沒有出現異常
OnlyOnCancelled:僅當被取消
NotOnCancelled:沒有被取消
處理異常
void Main(){Task rootTask = new Task(()=>{Console.WriteLine("root task completed");throw new Exception("root throwed exception");});rootTask.ContinueWith((Task previousTask)=>{Console.WriteLine("even root throw exception , I still run");}); rootTask.Start(); // waitfor input before exitingConsole.WriteLine("Press enter to finish");Console.ReadLine(); }
以上代碼中,第一個task中拋出了異常,Continue的Task仍然會繼續執行。可是Task被Finalized時異常就會拋出。
解決方案:
void Main(){Task rootTask = new Task(()=>{Console.WriteLine("root task completed");throw new Exception("root throwed exception");});var t2 = rootTask.ContinueWith((Task previousTask)=>{//if(previousTask.Status== TaskStatus.Faulted){throw previousTask.Exception.InnerException;}Console.WriteLine("even root throw exception , I still run");}); rootTask.Start(); try{t2.Wait();}catch(AggregateException ex){ex.Handle(inner=>{Console.WriteLine("exception handled in main thread"); return true;});} // waitfor input before exitingConsole.WriteLine("Press enter to finish");Console.ReadLine(); }
在Task中冒泡拋出異常,在主線程中等待最後那個Task的執行並對AggregateException進行處理。
建立子Task
建立子Task並附加在父Task上:
void Main(){ Task parentTask = new Task(() => {Console.WriteLine("parent task started");//create the first child taskTask childTask = new Task(() => {// writeout a message and waitConsole.WriteLine("Child task running");Thread.Sleep(1000);Console.WriteLine("Child task throwed exception");throw new Exception();} ,TaskCreationOptions.AttachedToParent);Console.WriteLine("start child task...");childTask.Start(); Console.WriteLine("parent task ended");});// startthe parent taskparentTask.Start(); // waitfor input before exitingConsole.WriteLine("Press enter to finish");Console.ReadLine();}
1. 父Task會拋出子Task中的異常
2. 父Task的狀態會受到所附加的子Task狀態的影響
Barrier的使用
class BankAccount {public int Balance {get;set;}} ; void Main(){//create the array of bank accountsBankAccount[] accounts = new BankAccount[6];for(int i = 0;i < accounts.Length; i++) {accounts[i] = new BankAccount();}//create the total balance counterint totalBalance = 0;//create the barrierBarrier barrier = new Barrier(3, (myBarrier) => { // zerothe balancetotalBalance= 0;// sumthe account totalsforeach(BankAccount account in accounts) {totalBalance+= account.Balance;}// writeout the balanceConsole.WriteLine("[From barrier :] Total balance: {0}",totalBalance);});//define the tasks arrayTask[] tasks = new Task[3];// loopto create the tasksfor(int i = 0;i < tasks.Length; i++) {tasks[i]= new Task((stateObj) => {//create a typed reference to the accountBankAccount account = (BankAccount)stateObj;// startof phaseRandom rnd = new Random();for(int j = 0;j < 1000; j++) {account.Balance+= 2;} Thread.Sleep(new Random().Next(3000)); Console.WriteLine("Task {0} waiting, phase {1} ",Task.CurrentId,barrier.CurrentPhaseNumber);//signal the barrier barrier.SignalAndWait(); account.Balance-= 1000;Console.WriteLine("barrier finished .");// endof phaseConsole.WriteLine("Task {0}, phase {1} ended",Task.CurrentId,barrier.CurrentPhaseNumber);//signal the barrierbarrier.SignalAndWait();},accounts[i]);} // startthe taskforeach(Task t in tasks) {t.Start();}// waitfor all of the tasks to completeTask.WaitAll(tasks);// waitfor input before exitingConsole.WriteLine("Press enter to finish");Console.ReadLine(); }
在以上代碼中,開啟了3個barrier和三個Task,在Task中為每個賬戶添加2000,然後給barrier發出同步訊號,當barrier收到3個訊號時,對帳號進行求和並儲存;當barrier完成邏輯後,控制權交給了每個Task,此時每個Task對account減1000,再次求和,最後結果為3000。
如果希望通過Cancel來控制barrier的行為,還可以在barrier中傳入tokenSource.Token:barrier.SignalAndWait(tokenSource.Token);並在Task中執行Cancel:tokenSource.Cancel()。
可以通過調用barrier.RemoveParticipant();來減少barrier的count。
CountEventDown
作用和Barrier類似,累計訊號數量,當訊號量達到指定數量,set event。
void Main(){ CountdownEvent cdevent = new CountdownEvent(5);//create a Random that we will use to generate// sleepintervalsRandom rnd = new Random();//create 5 tasks, each of which will wait for// arandom period and then signal the eventTask[] tasks = new Task[6];for(int i = 0;i < tasks.Length; i++) {//create the new tasktasks[i]= new Task(() => {// putthe task to sleep for a random period// up toone secondThread.Sleep(rnd.Next(500, 1000));//signal the eventConsole.WriteLine("Task {0} signalling event",Task.CurrentId);cdevent.Signal();});};//create the final task, which will rendezous with the other 5// usingthe count down eventtasks[5] = new Task(()=> {// waiton the eventConsole.WriteLine("Rendezvous task waiting");cdevent.Wait();Console.WriteLine("CountDownEvent has been set");}); // startthe tasksforeach(Task t in tasks) {t.Start();}Task.WaitAll(tasks); // waitfor input before exitingConsole.WriteLine("Press enter to finish");Console.ReadLine(); }
在以上代碼中,開啟了5個Task和1個count為5的CountDownEvent對象,每個Task中完成任務後分別對CountDownEvent發訊號,當湊齊5個訊號後,會列印出CountDownEvent has been set。
ManualResetEvent 和 AutoResetEvent
熟悉.net之前版本的應該都對它們很熟悉,用於在多線程環境中完成線程同步。區別在於,前者必須調用reset才能恢複訊號;而AutoResetEvent則會自動reset。在此不再贅述。
SemaphoreSlim
void Main(){ SemaphoreSlim semaphore = new SemaphoreSlim(3);//create the cancellation token sourceCancellationTokenSource tokenSource= new CancellationTokenSource(); //create and start the task that will wait on the eventfor(int i = 0;i < 10; i++) {Task.Factory.StartNew((obj)=> { semaphore.Wait(tokenSource.Token);// printout a message when we are releasedConsole.WriteLine("Task {0} released", obj); },i,tokenSource.Token);} //create and start the signalling taskTask signallingTask = Task.Factory.StartNew(() => {// loopwhile the task has not been cancelledwhile(!tokenSource.Token.IsCancellationRequested) {// go tosleep for a random periodtokenSource.Token.WaitHandle.WaitOne(500);//signal the semaphoresemaphore.Release(3);Console.WriteLine("Semaphore released");}// if wereach this point, we know the task has been cancelledtokenSource.Token.ThrowIfCancellationRequested();},tokenSource.Token);// askthe user to press return before we cancel// thetoken and bring the tasks to an endConsole.WriteLine("Press enter to cancel tasks");Console.ReadLine();//cancel the token source and wait for the taskstokenSource.Cancel();// waitfor input before exitingConsole.WriteLine("Press enter to finish");Console.ReadLine(); }
在以上代碼中,new了1個SemaphoreSlim對象並傳入3,開了10個Task線程,每當有訊號從Semaphore傳來時,列印Task[i]被release。同時開1個訊號線程,每500毫秒release3個Task。
可見,Semaphore的作用主要是可以選擇一次release多少個Task。
Producer / Consumer(生產者/消費者模式)
以下代碼中,new了1個BlockingCollection,類型為Deposit。開了3個生產者Task,每個生產者中建立20個Deposit對象並給Amount賦值為100。在主線程中等待生產者Task執行完畢,調用blockingCollection.CompleteAdding()方法。之後開1個消費者Task用於操作賬戶對象,迴圈判斷blockingCollection.IsCompleted屬性(生產者是否完成工作),從集合拿出存款對象,增加賬戶餘額。
範例程式碼:
class BankAccount {public int Balance {get;set;}}class Deposit {public int Amount {get;set;}} void Main(){BlockingCollection<Deposit> blockingCollection= new BlockingCollection<Deposit>(); var producers = new List<Task>();for(int i = 0;i < 3; i++) {var producer = Task.Factory.StartNew((obj) => {//create a series of depositsfor(int j = 0;j < 20; j++) {//create the transfervar randAmount = new Random().Next(100);Deposit deposit = new Deposit { Amount = randAmount};Thread.Sleep(newRandom().Next(200));// placethe transfer in the collectionblockingCollection.Add(deposit);Console.WriteLine(string.Format("Amount: {0} deposit Processed, index: {1}",randAmount, int.Parse(obj.ToString()) +j)); }}, i*20);producers.Add(producer);};//create a many to one continuation that will signal// theend of production to the consumerTask.Factory.ContinueWhenAll(producers.ToArray(),antecedents => {//signal that production has endedConsole.WriteLine("Signalling production end");blockingCollection.CompleteAdding();});//create a bank accountBankAccount account = new BankAccount();//create the consumer, which will update// thebalance based on the depositsTask consumer = Task.Factory.StartNew(() => {while(!blockingCollection.IsCompleted) {Deposit deposit;// tryto take the next itemif(blockingCollection.TryTake(outdeposit)) {//update the balance with the transfer amountaccount.Balance+= deposit.Amount;}}// printout the final balanceConsole.WriteLine("Final Balance: {0}", account.Balance);});// waitfor the consumer to finishconsumer.Wait();// waitfor input before exitingConsole.WriteLine("Press enter to finish");Console.ReadLine(); }