【发布时间】:2015-05-12 06:35:03
【问题描述】:
我有一个 MVC 控制器方法,它可以做很多事情,但它做的最后一件事是:
public void PerformCheckout(int salesAddressId)
{
try
{
...
...
// We just made a sale. Send emails to all market owners.
SendSalesEmailsAsync(master);
}
catch (System.Exception exception)
{
// Log the error
}
然后 SendSalesEmailesAsynch() 看起来像这样:
private async Task SendSalesEmailsAsync(SalesMaster salesMaster)
{
...
...
// Send an email to the owner of each marker
foreach(string market in markets)
await SendSalesEmailAsync(salesMaster, salesDetailList, market).ConfigureAwait(false);
}
SendSalesEmailAsynch() 看起来像这样:
// Send an email to a market owner
private async Task SendSalesEmailAsync(SalesMaster salesMaster, List<SalesDetail> salesDetail, string marketName)
{
...
...
Email email = new Email(new List<string> { sellerEmailAddress }, emailSubject, emailHtmlBody);
await email.SendAsync().ConfigureAwait(false);
最后,实际发送电子邮件的方法:
public async Task SendAsync()
{
// Create a network credentials object
var credentials = new NetworkCredential(azureUserName, azurePassword);
// Create an Web transport for sending the email
var transportWeb = new Web(credentials);
// Send the email. We don't care about the current context so let's run this in a thread pool context.
// For more information: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
await transportWeb.DeliverAsync(this._email).ConfigureAwait(false);
}
我对 Async 和 Await 还是很陌生。这一切看起来合适吗?另外,我不完全确定如果在发送电子邮件时发生错误,控制器操作方法中的 catch 块是否会被调用。
【问题讨论】:
-
这个问题是否足够相似以提供帮助:stackoverflow.com/questions/27798039/…
-
@neontapir - 也许但我不确定。我对 async / await 的了解还不够,不知道其中有多少适用。我怀疑这里有一位或多位专家可以快速查看我的情况并确定地告诉我。
-
我可以看看它,并告诉你这里有一些问题:P 用引用的完整答案解释它是快速部分变得更加复杂的地方。
-
@JohnathonSullinger 这段代码不完整,代码中有很多
...部分,这个问题在codereview 上不会很好接受。 -
@JohnathonSullinger 然后也许将用户指向您推荐的站点的help center。
标签: c# asp.net-mvc async-await