从我的理解主要事情之一async和await要做的就是让代码易于读写-但使用它们等于产卵后台线程来执行持续时间长的逻辑?
我正在尝试最基本的例子.我在内联添加了一些评论.你能为我澄清一下吗?
// I don't understand why this method must be marked as `async`.
private async void button1_Click(object sender, EventArgs e)
{
Task<int> access = DoSomethingAsync();
// task independent stuff here
// this line is reached after the 5 seconds sleep from
// DoSomethingAsync() method. Shouldn't it be reached immediately?
int a = 1;
// from my understanding the waiting should be done here.
int x = await access;
}
async Task<int> DoSomethingAsync()
{
// is …Run Code Online (Sandbox Code Playgroud) 我一直在玩 async 并且遇到了一些我以前没有注意到的行为,如果这是重复的,请告诉我,但是我的 google-fu 失败了,主要是因为我想不出体面的搜索条件:
给定一个简单的异步方法,它执行一些参数化工作:
async Task<String> Foo(int i)
{
await Task.Delay(i);
return i.ToString();
}
Run Code Online (Sandbox Code Playgroud)
以及在不同上下文中调用它并捆绑结果的调用方法:
async Task<Object> Bar()
{
var one = Foo(3000);
var two = Foo(5000);
var three = Foo(3000);
var x =
new
{
One = await one,
Two = await two,
Three = await three,
};
return x;
}
Run Code Online (Sandbox Code Playgroud)
这在 5 秒内完成(在 Linqpad6、.NET Core 3.1 中)。所以我假设每个任务同时运行。
但是,如果我将其更改为在开始时执行等待,则它会在 11 秒内完成。所以我假设每个任务都是按顺序运行的。
async Task<Object> Bar()
{
var one = await Foo(3000);
var two = await Foo(5000);
var three …Run Code Online (Sandbox Code Playgroud)