private void button1_Click(object sender, EventArgs e)
{
Task<int> task = Fun3();
Task task2 = Func1();
Console.WriteLine("等待前输出");
await task;
await task2;
//Task.WaitAll(task, task2); //这种写法会阻塞主线程,导致死锁
Console.WriteLine("等待后输出");
Console.WriteLine(task.Result);
}
private static async Task Func1()
{
await Task.Run(() =>
{
Thread.Sleep(2000);
Console.WriteLine("2222");
});
}
private static async Task<int> Fun3()
{
int ret = 0;
await Task.Run(() =>
{
var result = Task.Run(async () => await Fun4());
if (result.Result > 0)
{
Console.WriteLine("正确流程");
}
else
{
Console.WriteLine("错误流程");
ret = 1;
}
});
return ret;
}
private static async Task<int> Fun4()
{
int ret = 0;
await Task.Run(() =>
{
if (3 > 2)
ret = 1;
});
return ret;
}
Fun1和Func3是2个单独的任务,可以异步执行。Fun3执行时需依赖Fun4的结果,才能执行后续。上边的写法看起来功能可以实现,不过感觉写法有点奇怪,之前用的比较少,请熟悉的人帮忙看下。如果写法有问题,需要怎么修改?