假设我的服务正在运行,并且我在该服务中使用了用于发送电子邮件通知的代码。 “EmailNotification”方法是异步和等待的。
EmailNotification代码:
public async task EmailNotification()
{
try
{
//code here
using (SmtpClient smtp = new SmtpClient())
{
//mail sending
await smtp.Send(mailMessage);
}
}
Catch(Exception ex)
{
}
}
在我的一些测试方法中使用了 EmailNotification 方法:
public void test()
{
EmailNotification();
}
我的问题:
1)如果我的目标方法测试不是异步类型,我如何记录异步和等待方法的执行?
2)是否可以在非异步类型中使用异步方法,如上面的 ia m using in test method?
最佳答案
How can i log execptions of async and await method if my destination method test is not of type async?
async
方法返回的任务将包含该方法的所有异常。但是,以这种“即发即弃”的方式调用它意味着返回的任务将被忽略。因此,您必须在 async
方法(已经存在)中有一个 try
/catch
并登录 捕获
。
Is it possible to use async method in non async type like above ia m using in test method?
可能吗?当然,它会编译并运行。
好主意?可能不是。
在 ASP.NET 上,在 HTTP 请求之外 完成的任何工作都不能保证完成。当您的代码调用 EmailNotification
时,它开始一些工作然后完成 HTTP 请求(通过发送响应)。发送电子邮件的工作无需 HTTP 请求即可完成,如果您的应用被回收,则可能会丢失。
如果您完全同意电子邮件偶尔消失而没有任何日志或任何其他出现问题的迹象,那么这是一个很好的方法。如果您对此不满意,那么您将需要一个更强大的解决方案(例如 proper distributed architecture ,正如我在我的博客中所描述的那样)。或者,您可以使用 SendGrid 等电子邮件服务外包这部分内容。
关于c# - 在非异步方法中调用异步并记录异步等待方法的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37782177/