原文: 5天玩转C#并行和多线程编程 —— 第四天 Task进阶
using System;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("1.1 Task的嵌套 (父不等子操作完即结束)");
TaskMethod1_1();
Console.WriteLine("1.2 Task的嵌套(父等子操作完再结束, 省得我们写Task.WaitAll了,外层的Task会自动等待所有的子Task完成才向下走。)");
TaskMethod1_2();
Console.WriteLine("1.3 Task的嵌套 (Task协作)");
TaskMethod1_3();
Console.WriteLine("2.1 Task的异常处理 用 Exception (提示:发生一个或多个错误)");
TaskMethod2_1();
Console.WriteLine("2.2 Task的异常处理 用 AggregateException (提示真正的错误根源)");
TaskMethod2_2();
Console.Read();
}
private static void TaskMethod2_2()
{
try
{
var pTask = Task.Factory.StartNew(() =>
{
var cTask = Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(2000);
throw new Exception("cTask Error!");
Console.WriteLine("Childen task finished!");
});
throw new Exception("pTask Error!");
Console.WriteLine("Parent task finished!");
});
pTask.Wait();
}
catch (AggregateException ex)
{
foreach (Exception inner in ex.InnerExceptions)
{
Console.WriteLine(inner.Message);
}
}
Console.WriteLine("Flag");
}
private static void TaskMethod2_1()
{
try
{
var pTask = Task.Factory.StartNew(() =>
{
var cTask = Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(2000);
throw new Exception("cTask Error!");
Console.WriteLine("Childen task finished!");
});
throw new Exception("pTask Error!");
Console.WriteLine("Parent task finished!");
});
pTask.Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Flag");
}
private static void TaskMethod1_3()
{
Task.Factory.StartNew(() =>
{
var t1 = Task.Factory.StartNew<int>(() =>
{
Console.WriteLine("Task 1 running...");
return 1;
});
t1.Wait(); //等待任务一完成
var t3 = Task.Factory.StartNew<int>(() =>
{
Console.WriteLine("Task 3 running...");
return t1.Result + 3;
});
var t4 = Task.Factory.StartNew<int>(() =>
{
Console.WriteLine("Task 2 running...");
return t1.Result + 2;
}).ContinueWith<int>(task =>
{
Console.WriteLine("Task 4 running...");
return task.Result + 4;
});
Task.WaitAll(t3, t4); //等待任务三和任务四完成
var result = Task.Factory.StartNew(() =>
{
Console.WriteLine("Task Finished! The result is {0}", t3.Result + t4.Result);
});
});
}
private static void TaskMethod1_2()
{
var pTask = Task.Factory.StartNew(() =>
{
var cTask = Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("1.2Childen task finished!");
}, TaskCreationOptions.AttachedToParent);
Console.WriteLine("1.2Parent task finished!");
});
pTask.Wait();
Console.WriteLine("Flag1.2");
}
private static void TaskMethod1_1()
{
var pTask = Task.Factory.StartNew(() =>
{
var cTask = Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("1.1Childen task finished!");
});
Console.WriteLine("1.1Parent task finished!");
});
pTask.Wait();
Console.WriteLine("Flag1.1");
}
}
}