![Improving your C# Skills](https://wfqqreader-1252317822.image.myqcloud.com/cover/888/36698888/b_36698888.jpg)
上QQ阅读APP看书,第一时间看更新
Dataflow pattern
The dataflow pattern is a generalized pattern with a one-to-many and a many-to-one relationship. For example, the following diagram represents two tasks, Task 1 and Task 2, that execute in parallel, and a third task, Task 3, that will only start when both of the first two tasks are completed. Once Task 3 is completed, Task 4 and Task 5 will be executed in parallel:
![](https://epubservercos.yuewen.com/18A014/19470381908825606/epubprivate/OEBPS/Images/29e7a6d4-7719-44fe-b1f8-d56fb24f598e.png?sign=1738929128-8pLhMY7wcskdBlroVNqHhI9akrftiACW-0-b1d6231276f14558e661a66c362df25e)
We can implement the preceding example using the following code:
static void Main(string[] args) {
//Creating two tasks t1 and t2 and starting them at the same //time Task<int> t1 = Task.Factory.StartNew(() => { return Task1(); }); Task<int> t2 = Task.Factory.StartNew(() => { return Task2(); });
//Creating task 3 and used ContinueWhenAll that runs when both the
//tasks T1 and T2 will be completed Task<int> t3 = Task.Factory.ContinueWhenAll(
new[] { t1, t2 }, (tasks) => { return Task3(); });
//Task 4 and Task 5 will be started when Task 3 will be completed.
//ContinueWith actually creates a continuation of executing tasks
//T4 and T5 asynchronously when the task T3 is completed
Task<int> t4 = t3.ContinueWith((antecendent) => { return Task4(); });
Task<int> t5 = t3.ContinueWith((antecendent) => { return Task5(); }); Console.Read(); }
//Implementation of Task1 public static int Task1() { Thread.Sleep(1000); Console.WriteLine("Task 1 is executed"); return 1; }
//Implementation of Task2 public static int Task2() { Thread.Sleep(1000); Console.WriteLine("Task 2 is executed"); return 1; } //Implementation of Task3 public static int Task3() { Thread.Sleep(1000); Console.WriteLine("Task 3 is executed"); return 1; } Implementation of Task4 public static int Task4() { Thread.Sleep(1000); Console.WriteLine("Task 4 is executed"); return 1; }
//Implementation of Task5 public static int Task5() { Thread.Sleep(1000); Console.WriteLine("Task 5 is executed"); return 1; }