我在YT上观看了一些视频,这些视频描述了SMS Manager的Event Hanlders。我想用Email Manager建立类似的东西:
public class OfferEmailManager
{
public async void OnSecurityDepositAdded(object source, SecurityDepositEventArgs eventArgs)
{
EmailObject email = new EmailObject();
//preparing email object (subject, body, from, to)
var result = await EmailAPI.Instance.SendEmail(email);
}
private string PrepareSecurityDepositAddMail(SecurityDepositEventArgs eventArgs)
{
//preparing mail body
}
}
似乎一切正常,但是发送电子邮件是异步的,我不得不使OnSecurityDepositAdded
异步。当SecurityDeposit
添加到控制器中的数据库时,我想发送电子邮件:
public EventHandler<SecurityDepositEventArgs> SecurityDepostAdded;
protected virtual void OnSecurityDepositAdded(SecurityDeposit securityDeposit, Offer offer)
{
SecurityDepositAdded?.Invoke(this, new SecurityDepositEventArgs()
{
//values
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddSecurityDeposit(SecurityDepositCreateViewModel model)
{
Offer offer = db.Offers.Find(model.ID);
OfferEmailManager manager = new OfferEmailManager();
SecurityDepositAdded += manager.OnSecurityDepositAdded;
SecurityDeposit securityDeposit = new SecurityDeposit()
{
// values
};
db.SecurityDeposits.Add(securityDeposit);
try
{
db.SaveChanges();
OnSecurityDepositAdded(securityDeposit, offer);
return RedirectToAction("Details", new { id = model.ID });
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.Message;
return View(model);
}
}
最后,它非常适合return RedirectToAction
,我收到了电子邮件,但也有例外情况
异步完成的异步模块或处理程序 操作仍在等待中
如何处理此异常?