首页 > 解决方案 > “应用程序处于中断模式” C# 使用 throw 冒泡异常时

问题描述

当我抛出异常时,我的函数将其冒泡并在任务异常中捕获它,而不是继续它会破坏代码-下面是我的代码

public override void Run()
{
    SendRenewalsEmail("ddd@xxx.com", " Email Body from test More", "Test Email from Service another Test");
}

private async void SendRenewalsEmail(string userEmail, string emailBody, string emailSubject)
{
    string replyFromEmailAddress = "renewals@xxx.net";
    string cc = "";
    string bcc = "ccc@xxxx.com";
    SMTPMailHelperAsync sMTPMailHelperAsync = new SMTPMailHelperAsync();
    var x= await sMTPMailHelperAsync.SendEmailAsync(userEmail, cc, bcc, emailSubject, SMTPMailHelperAsync.ProcessTemplate(emailBody, "Renewals.html", emailSubject), replyFromEmailAddress);

    if (x.MailSent)
    {
        throw new Exception("after mail Test more service");
    }
}

以及它被捕获的任务

var task=  Task<PluginInstance>.Run<PluginInstance>(() => {
    thisPlugin.LastRunStart = DateTime.Now.ToLocalTime();
    try
    {
        thisPlugin.Plugin.Run();
        thisPlugin.LastRunStatus = Enums.RunStatus.Success;
        thisPlugin.LastRunMessage = "";
    }
    catch (Exception ex)
    {
        thisPlugin.LastRunStatus = Enums.RunStatus.Failed;
        thisPlugin.LastRunMessage = ex.Message;
    }
    thisPlugin.LastRunEnd = DateTime.Now.ToLocalTime();
    return thisPlugin;
});

ListOfTask.Add(task);

现在我试图在任务异常中捕获异常但不是。低于异常 在此处输入图像描述

标签: c#-4.0task-parallel-library

解决方案


您不得使用async void. 这是一种特殊情况,仅为事件处理程序保留。您的async方法必须返回Task

private async Task SendRenewalsEmail(…)

然后,你的Plugin.Run方法就坏了。它也应该如此async

一旦你开始async - await,你就做到了。


推荐阅读