[英]Nested Task<T> calls without async/await
This is kind of related to the following post: Why use Async/await all the way down 这与以下帖子有关: 为什么一直使用Async / await
I am curious what happens in the following scenario: 我很好奇在以下场景中会发生什么:
Updated due to comment: 由于评论而更新:
async Task FooAsync()
{
await Func1();
// do other stuff
}
Task Func1()
{
return Func2();
}
async Task Func2()
{
await tcpClient.SendAsync();
// do other stuff
}
Does this whole process becomes a blocking call? 整个过程是否会成为阻止呼叫? Or because Func1() is actually awaited on, the UI can go and work on something else?
或者因为实际上正在等待Func1(),UI可以继续工作吗? Ultimately is it necessary to add the async/await on Func1()?
最终是否需要在Func1()上添加async / await? I've played around with it but I don't actually notice any difference, hence the question.
我玩过它但我实际上没有发现任何差异,因此问题。 Any insight would be great, thanks!
任何见解都会很棒,谢谢!
Async
and await
are just compiler features. Async
和await
只是编译器功能。
Without await
calling async method will cause it to execute synchronous (blocking) way.. 没有
await
调用异步方法会导致它执行同步(阻塞)方式..
When you are writing await
all code bellow await
is wrapped in Task.ContinueWith()
Method by compiler automaticly, this means that when task is finished code below is executed later 当你写
await
所有代码波纹管await
被包裹在Task.ContinueWith()
由编译器全自动方法,这意味着,当任务完成下面的代码在以后执行
public async Task<int> method2(){
return Task.FromResult(1);
}
public void method1(){
await method2()
Console.WriteLine("Done");
}
will translate something like : 将翻译如下:
public Task<int> method2(){
return Task.FromResult(1);
}
public void method1(){
method2().ContinueWith(x => {
Console.WriteLine("Done");
});
}
The only problem of not making Func1
and async
method and not await
ing Func2
in it is that any thrown exception won't show Func1
. 没有制作
Func1
和async
方法而不await
Func2
的唯一问题是任何抛出的异常都不会显示Func1
。
The bottom line is that await
works on awaitables and Task
/ Task<T>
are awaitables . 最重要的是
await
适用于awaitables和Task
/ Task<T>
是等待的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.