为什么“& async void&"方法同步运行? [英] Why does an "async void" method run synchronously?

查看:74
本文介绍了为什么“& async void&"方法同步运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处埃里克·利珀特(Eric Lippert)说:

Here Eric Lippert says:

无法等待void返回的异步方法;这是大火, 忘记"方法. 它确实异步工作 ...

A void returning async method cannot be awaited; it is a "fire and forget" method. It does work asynchronously...

它确实可以异步工作吗?

It does work asynchronously right?

为了测试这一点,我制作了一个Windows窗体应用程序并处理了一个任意事件.在处理程序内部,我开始进行繁重的计算.显然,它阻止了UI的响应:

To test that, I made a windows form application and handled one arbitrary event. Inside handler, I started a heavy computation. Clearly, it blocks the UI to respond:

this.KeyPress += Form1_KeyPressed;
....
private async void Form1_KeyPressed(object sender, EventArgs e)
{
   for(int i=0; i<int.max; i++)
      ;
}

Eric的答案中我缺少什么?

What am I missing in Eric's answer?

推荐答案

Eric的答案中我缺少什么?

What am I missing in Eric's answer?

我的意思是它的工作方式与任何其他异步方法一样.当您在异步方法中等待某些内容时,该方法的其余部分将被标记为等待的内容的延续.无论异步方法是否无效,都是如此.

I meant that it works like any other asynchronous method. When you await something in an asynchronous method the remainder of the method is signed up as the continuation of the awaited thing. That is true whether the asynchronous method is void or not.

在您的示例中,代码的工作原理与返回任务的异步方法完全相同.尝试更改您的方法以返回任务,您将看到它的行为完全相同.

In your example your code works exactly like an asynchronous method that returns a task. Try changing your method to return a task, and you'll see it behaves exactly the same.

请记住,异步"并不表示我在另一个线程上同时运行".这意味着该方法可能在其操作完成之前返回".在操作完成之前可能返回的点标记为等待".您尚未用"await"标记任何内容.

Remember, "async" does not mean "I run concurrently on another thread". It means "the method may return before its action is completed". The points at which it may return before its action is completed are marked with "await". You haven't marked anything with "await".

我怀疑您相信异步需要并发的神话.再一次:异步只是意味着方法可以在其工作完成之前返回.您开始煮一些鸡蛋,门铃响起,然后将包装从门廊上取下来,煮完鸡蛋,然后打开包装. 煮鸡蛋"和获取邮件"作业不是并发的 -您从未同时做过 .它们是异步.

I suspect you believe the myth that asynchrony requires concurrency. Again: asynchrony simply means that a method can return before its work is done. You start cooking some eggs, the doorbell rings, you go get the package off the porch, you finish cooking the eggs, you open the package. The "cook eggs" and "fetch the mail" jobs are not concurrent -- you never did them at the same time. They are asynchronous.

这篇关于为什么“&amp; async void&amp;"方法同步运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆