【发布时间】:2015-03-23 20:52:10
【问题描述】:
我正在发送“异步”电子邮件。
我使用一个通用的“异步”函数来调用电子邮件函数,因为我不需要等待电子邮件的响应。
public Task SendAsync(....)
{
....
return mailClient.SendMailAsync(email);
}
我需要从 async 和 sync 函数中调用它。
从异步函数调用
public async Task<ActionResult> AsyncFunction(...)
{
....
EmailClass.SendAsync(...);
....
// gives runtime error.
// "An asynchronous module or handler completed while an asynchronous operation was still pending..."
// Solved by using 'await EmailClass.SendAsync(...);'
}
从同步函数调用
public ActionResult syncFunction(...)
{
....
EmailClass.SendAsync(...);
....
// gives runtime error.
// "An asynchronous operation cannot be started at this time..."
// Solved by converting the function as above function
}
这两个函数都会给出运行时错误,然后通过在异步函数中使用 await 关键字来解决。
但是通过使用await,它违背了我的running it on background without waiting for response 的目的。
如何在不等待响应的情况下调用异步函数?
【问题讨论】:
-
您的根本问题是误解了在这种情况下编写异步代码的好处是触发并忘记-这不是这种异步的主要目的,它是在您释放线程时 等待任务完成——而不是简单地等待它。
-
是的,我想我现在明白了。
标签: c# asynchronous