从我的理解主要事情之一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) 任务或任务<TResult>对象是等待的,因此我们可以在返回值为Task或Task <TResult>的对象上使用await键.任务或任务<TResult>是最常用的等待对象.
我们也可以定义我们自己的等待对象.对象应该具有以下资格.
我的问题是为什么微软没有提供限制这些等待对象的界面?目前实现等待对象的方法有点复杂.