开火并忘记而没有异步的空虚 [英] Fire and forget without async void
问题描述
我有3种方法,其中第一种结果将在接下来的两种方法中使用,并且预期不会返回任何数据.
I have three methods where the first result will be used in the next two methods and no data expected to be return back.
result= await DataAccess.Query(param); //Query
await DataAccess.Create(result);
await DataAccess.Update(result);
-
我真的需要在这里使用await吗?
Do I really need to use await here?
使用异步void是否正确在创建和更新功能中?
is it correct to use async void in create and update function?
推荐答案
没有数据会返回.
no data expected to be return back.
那错误呢?如果发生错误,是否需要返回错误代码,或者即使 Create
或 Update
失败, 200 OK
是否可以接受?
What about errors? Do you need to return an error code if an error occurs, or is 200 OK
acceptable even if the Create
or Update
fails?
我假设您需要一个错误代码.99.99%的电话愿意.
I'm assuming you'll need an error code. 99.99% of calls do.
我真的需要在这里使用await吗?
Do I really need to use await here?
好吧,如果您想要同步方法,则可以只调用同步API.不过,我不知道您为什么要这么做.
Well, if you want synchronous methods, then you can just call synchronous APIs. I don't know why you would want that, though.
提醒一下: await
与无关与返回浏览器无关.它与减少线程池线程的使用量有关,从而使您的服务器可以进一步扩展.
As a reminder: await
has nothing to do with returning to the browser. It has everything to do with using fewer thread pool threads, allowing your server to scale further.
在创建和更新功能中使用异步void是否正确?
is it correct to use async void in create and update function?
不.永远不会.
什么是开火而在这里忘记的正确方法?
what will be the right approach to do a fire and forget here?
正确的方法是不要".即弃式操作很难正确执行,事实上,由于您需要输入错误代码,因此不能进行即弃式操作.
The correct approach is "don't". Fire-and-forget is difficult to do correctly, and in fact since you need an error code, you can't do fire-and-forget.
我写了很多有关一劳永逸"的内容-包括为什么 StartNew
和 Task.Run
是无效的解决方案-
I write more about fire-and-forget - including why StartNew
and Task.Run
are invalid solutions - on my blog. Note that the only fully reliable solution (including upgrade scenarios) is the last one (distributed architecture).
如果异步仅用于同步运行,那么没有等待的异步的意义何在?没有该关键字,我什至可以实现这一目标.
what is the significance of async without await if it only used to run synchronously? I can even achieve that without that keyword.
它正在按顺序运行 (而不是同步(阻塞线程)). async
的好处是可以实现更大的可伸缩性.有关更多信息,请参见我的 ASP上 async
简介.NET 文章.
It's running serially (in order), not synchronously (blocking a thread). The benefit of async
is to allow greater scalability. For more information, see my intro to async
on ASP.NET article.
这篇关于开火并忘记而没有异步的空虚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!