![Improving your C# Skills](https://wfqqreader-1252317822.image.myqcloud.com/cover/888/36698888/b_36698888.jpg)
上QQ阅读APP看书,第一时间看更新
Pipeline pattern
The pipeline pattern is commonly used in scenarios where we need to execute the asynchronous tasks in sequence:
![](https://epubservercos.yuewen.com/18A014/19470381908825606/epubprivate/OEBPS/Images/f7f51cd1-c8dd-40b7-9d1f-130dbafb444b.png?sign=1738834207-1ycjZMZDAC0c1aig9zh4tNOKntkKqDXL-0-bab1924f27981f526fb78ad30712b7af)
Consider a task where we need to create a user record first, then initiate a workflow and send an email. To implement this scenario, we can use the ContinueWith method of TPL. Here is a complete example:
static void Main(string[] args) { Task<int> t1 = Task.Factory.StartNew(() => { return CreateUser(); }); var t2=t1.ContinueWith((antecedent) =>
{ return InitiateWorkflow(antecedent.Result); }); var t3 = t2.ContinueWith((antecedant) =>
{ return SendEmail(antecedant.Result); }); Console.Read(); } public static int CreateUser() { //Create user, passing hardcoded user ID as 1 Thread.Sleep(1000); Console.WriteLine("User created"); return 1; } public static int InitiateWorkflow(int userId) { //Initiate Workflow Thread.Sleep(1000); Console.WriteLine("Workflow initiates"); return userId; } public static int SendEmail(int userId) { //Send email Thread.Sleep(1000); Console.WriteLine("Email sent"); return userId; }