【发布时间】:2019-04-10 12:33:15
【问题描述】:
有时我需要启动一个运行速度很慢的异步作业。我不在乎那份工作是否成功,我需要继续处理我当前的线程。
就像有时我需要发送一封电子邮件或短信,它的工作速度很慢。我需要尽快回复网络客户端,所以我不想await它。
我用谷歌搜索了这个问题,有些文章建议我这样写:
// This method has to be async
public async Task<Response> SomeHTTPAction()
{
// Some logic...
// ...
// Send an Email but don't care if it successfully sent.
Task.Run(() => _emailService.SendEmailAsync());
return MyRespond();
}
或者像这样:
// This method has to be async
public async Task<Response> SomeHTTPAction()
{
// Some logic...
// ...
// Send an Email but don't care if it successfully sent.
Task.Factory.StartNew(() => _emailService.SendEmailAsync());
return MyRespond();
}
会有一个警告说:before the call is completed. Consider applying the 'await' operator to the result of the call.
如果我真的awaited 怎么办? C# 中“触发并忘记”的最佳实践是什么,只需调用异步方法而不等待其完成?
【问题讨论】:
-
只是不要将函数标记为异步,所以函数不应该期望它的结果被等待?
-
更好的方法是让这些操作在进程之外运行,即发布到像 rabbitmq 这样的队列,让订阅者接收这些消息,然后发送电子邮件/短信
-
到目前为止你发现了什么信息? “C# async fire and forget”的快速谷歌显示有很多可用的资源..
-
这真的不是设计的问题吗?在您知道操作是否完成之前返回
MyRespond有什么意义?
标签: c# asynchronous