一:Task中的枚举
None = 0,
PreferFairness = 1,
LongRunning = 2,
AttachedToParent = 4,
DenyChildAttach = 8,
HideScheduler = 16,
RunContinuationsAsynchronously = 64
二:任务延续中的枚举
1 | None = 0, |
三:演示
TaskCreationOptions:
1.AttachedToParent:子线程和父线程同步
Task task = new Task(() =>
{
Task task1 = new Task(() =>
{
Thread.Sleep(100);
Console.WriteLine("task1");
}, TaskCreationOptions.AttachedToParent);
Task task2 = new Task(() =>
{
Thread.Sleep(10);
Console.WriteLine("task2");
}, TaskCreationOptions.AttachedToParent);
task1.Start();
task2.Start();
});
task.Start();
task.Wait();
Console.WriteLine("我是主线程");
2.DenyChildAttach:不让子任务附加到父任务中
Task task = new Task(() =>
{
Task task1 = new Task(() =>
{
Thread.Sleep(100);
Console.WriteLine("task1");
}, TaskCreationOptions.AttachedToParent);
Task task2 = new Task(() =>
{
Thread.Sleep(10);
Console.WriteLine("task2");
}, TaskCreationOptions.AttachedToParent);
task1.Start();
task2.Start();
}, TaskCreationOptions.DenyChildAttach);
task.Start();
task.Wait();
Console.WriteLine("我是主线程");
3.HideScheduler:子任务默认不调用父类的Task的Scheduler,而是使用默认的
4.LongRunning:长时间运行的任务,建议使用此选项,或者建议使用Thread而不是ThreadPool,如果长期租用不还给ThreadPool,ThreadPool会开启新的线程,如果此时租用线程归还,这回导致ThreadPool线程过多,销毁和调度都是一个很大的麻烦。
Task task1 = new Task(() =>
{
Thread.Sleep(100);
Console.WriteLine("task1");
}, TaskCreationOptions.LongRunning);
task1.Start();
task1.Wait();
Console.WriteLine("我是主线程!!!");
Console.Read();
5.PreferFairness:会将Task放入到ThreadPool的全局变量中,让word thread进行争抢,默认情况会放到task的一个本地队列中。