Task.WhenAny()
Task.WhenAll()
这两个与waitALL,waitAny是有区别的
when是异步的,wait是同步的
例子
Task[] ts = new Task[] {new Task(()=> { Thread.Sleep(3000); Console.WriteLine("触发1"); }),
new Task(() => { Thread.Sleep(9000); Console.WriteLine("触发2"); }) };
Task.WhenAny(ts).ContinueWith((task) => { Console.WriteLine("OK"+task.Result); });
ts[0].Start();
ts[1].Start();
Console.WriteLine("主程序");
Console.ReadKey();
或者
Task[] ts = new Task[] {Task.Factory.StartNew(()=> { Thread.Sleep(3000); Console.WriteLine("触发1"); }),
Task.Factory.StartNew(() => { Thread.Sleep(9000); Console.WriteLine("触发2"); }) };
Task.WhenAny(ts).ContinueWith((task) => { Console.WriteLine("OK"+task.Result); });
Console.WriteLine("主程序");
主程序会很快走完,下面就会走异步的任务
下面是连续执行后续任务的例子
static void DoOnFirst()
{
Console.WriteLine("doing some task test");
Thread.Sleep(3000);
}
static void DoOnSecond(Task t)
{
Console.WriteLine("task {0} finished",t.Id);
Console.WriteLine("this task id {0}", Task.CurrentId);
Console.WriteLine("do some cleanup");
Thread.Sleep(3000);
}
static void Main(string[] args)
{
//callMethod();
Task t1 = new Task(DoOnFirst);
t1.Start();
Task t2 = t1.ContinueWith(DoOnSecond);
Task t3 = t2.ContinueWith(DoOnSecond);
Task t4 = t3.ContinueWith(DoOnSecond);
Console.ReadKey();
}
Task 返回值,需要泛型Task
static string DoOnFirst()
{
Console.WriteLine("doing some task test");
Thread.Sleep(3000);
return "DoOnFirst";
}
static void DoOnSecond(Task t)
{
Console.WriteLine("task {0} finished",t.Result);
Console.WriteLine("this task id {0}", Task.CurrentId);
Console.WriteLine("do some cleanup");
Thread.Sleep(3000);
}
static void Main(string[] args)
{
//callMethod();
Task t1 = new Task(DoOnFirst);
t1.Start();
Task t2 = t1.ContinueWith(DoOnSecond);
//Task t3 = t2.ContinueWith(DoOnSecond);
//Task t4 = t3.ContinueWith(DoOnSecond);
Console.ReadKey();
}
单独阻塞一个Task(当前线程阻塞)
Task t1 = new Task(DoOnFirst);
t1.Start();
t1.GetAwaiter().GetResult();