在ASP.Net Webforms上捕获线程异常

时间:2015-04-14 09:49:21

标签: c# asp.net multithreading pdf exception-handling

我有私有方法,尝试生成pdf文件,然后使用此pdf发送电子邮件。如果一切正常,则此方法将表单上的文本更改为" Pdf已成功生成"。

我的方法:

private void RegenerateSubmissionPdf(int submissionId)
{
    var submissionPath = PublisherConfigurationManager.SubmissionPath + submissionId;

    var tasks = new List<Task>
    {
        HttpContext.Current.GeneratePdfTask(submissionPath, submissionId, PublisherConst.SubmissionPdfName,
            _objSubmission.SaveSubmissionPdf)
    };

    tasks.SendEmailTasks(u => SendRegenerateSubmissionPdfEmail(submissionId, u));
}

返回Task的方法:

public static Task GeneratePdfTask(this HttpContext context, string path, int submissionId, string pdfName, Action<int, byte[]> postAction = null)
{
    var local = context;
    return Task.Factory.StartNew(() =>
    {
        HttpContext.Current = local;
        SessionHelper.Set(SessionKey.IsPdfRendering, true);
        var pdfFile = new PdfGenerator().Generate(path, pdfName, submissionId);
        if (postAction != null && pdfFile != null)
        {
            postAction(submissionId, pdfFile);
        }

    });
}

在上一种方法中,有时我会遇到异常(可能是路径错误,某些图像缺失或其他原因)。我找到this solution,但不知道如何将其应用到我的案例中。

2 个答案:

答案 0 :(得分:0)

你试过这个:

private void RegenerateSubmissionPdf(int submissionId)
{
    var submissionPath = PublisherConfigurationManager.SubmissionPath + submissionId;

    var tasks = new List<Task>
    {
        HttpContext.Current.GeneratePdfTask(submissionPath, submissionId, PublisherConst.SubmissionPdfName,
            _objSubmission.SaveSubmissionPdf)
    };
    tasks.ForEach(t => t.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted));
    tasks.SendEmailTasks(u => SendRegenerateSubmissionPdfEmail(submissionId, u));
}

private void ExceptionHandler(Task task)
{
    // Handle exception
}

在列表中创建并启动任务后,如果抛出异常,则为每个任务分配一个延续。但根据您的代码,我无法看到对任务列表的需求。您可以简单地使用任务对象并为其指定延续。

答案 1 :(得分:0)

据我了解,SendEmailTasks是一种扩展方法,但您只能使用一个任务,如下所示:

private void RegenerateSubmissionPdf(int submissionId)
{
    var submissionPath = PublisherConfigurationManager.SubmissionPath + submissionId;

    var task = HttpContext.Current.GeneratePdfTask(submissionPath, submissionId, PublisherConst.SubmissionPdfName,
            _objSubmission.SaveSubmissionPdf);
    task.ContinueWith(t =>  
      SendRegenerateSubmissionPdfEmail(submissionId, task),  
      TaskContinuationOptions.OnlyOnRanToCompletion);
    task.ContinueWith(t =>  
      HandleException(task.Exception),  
      TaskContinuationOptions.OnlyOnFaulted);
    await task;
}

如果没有异常,这种方法将继续执行,并且如果有异常将处理异常。并考虑使用await结构或Run方法代替StartNew(Stephen Cleary的great article about this)。