【问题标题】:“The application is in break mode" C# when using throw to bubble out the exception“应用程序处于中断模式” C# 使用 throw 冒泡异常时
【发布时间】:2019-01-17 00:19:59
【问题描述】:

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

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.0 task-parallel-library


    【解决方案1】:

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

    private async Task SendRenewalsEmail(…)
    

    那么,你的Plugin.Run 方法就坏了。也应该是async

    一旦您从async - await 开始,您就可以做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 2015-09-23
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 2015-01-24
      • 1970-01-01
      相关资源
      最近更新 更多