【问题标题】:A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property通过等待任务或访问其异常属性未观察到任务的异常
【发布时间】:2012-02-29 21:38:23
【问题描述】:

这些是我的任务。我应该如何修改它们以防止此错误。我检查了其他类似的线程,但我正在使用等待并继续。那么这个错误是怎么发生的呢?

在等待任务或访问其异常属性时未观察到任务的异常。结果,未观察到的异常被终结器线程重新抛出。

    var CrawlPage = Task.Factory.StartNew(() =>
{
    return crawlPage(srNewCrawledUrl, srNewCrawledPageId, srMainSiteId);
});

var GetLinks = CrawlPage.ContinueWith(resultTask =>
{
    if (CrawlPage.Result == null)
    {
        return null;
    }
    else
    {
        return ReturnLinks(CrawlPage.Result, srNewCrawledUrl, srNewCrawledPageId, srMainSiteId);
    }
});

var InsertMainLinks = GetLinks.ContinueWith(resultTask =>
{
    if (GetLinks.Result == null)
    {

    }
    else
    {
        instertLinksDatabase(srMainSiteURL, srMainSiteId, GetLinks.Result, srNewCrawledPageId, irCrawlDepth.ToString());
    }

});

InsertMainLinks.Wait();
InsertMainLinks.Dispose();

【问题讨论】:

  • 嗯,没有什么明显的错误。您是否尝试过在调试器中运行以查看是否可以确定哪个任务被泄露? (顺便说一句,您在这里有一些奇怪的编码约定:您使用 PascalCase 表示本地变量,使用 camelCase 表示方法,这与通常的 .NET 约定相反。)
  • 感谢您的回答。那么代码中可能还有其他不正确的地方。我会检查:)
  • 如果在执行任务时抛出未处理的异常,您会收到此错误。您是否尝试过将对 ReturnLinks 和 insertLinksDatabase 的调用包含在 try/catch 块中?
  • 感谢乔希的回答。我想那里发生的意外错误不应该使应用程序崩溃,因为它们也在另一个任务中被调用。它们应该被处理,因为它们在另一个任务中被调用并通过 ContinueWith 处理。现在正在尝试别的东西。如果再次发生错误,我会尝试您的建议。

标签: c# wpf exception error-handling task


【解决方案1】:

你没有处理任何异常。

改变这一行:

InsertMainLinks.Wait();

到:

try { 
    InsertMainLinks.Wait(); 
}
catch (AggregateException ae) { 
    /* Do what you will */ 
}

一般来说:为了防止终结器重新抛出任何源自工作线程的未处理异常,您可以:

等待线程并捕获 System.AggregateException,或者只是读取异常属性。

EG:

Task.Factory.StartNew((s) => {      
    throw new Exception("ooga booga");  
}, TaskCreationOptions.None).ContinueWith((Task previous) => {  
    var e=previous.Exception;
    // Do what you will with non-null exception
});

Task.Factory.StartNew((s) => {      
    throw new Exception("ooga booga");  
}, TaskCreationOptions.None).ContinueWith((Task previous) => {      
    try {
        previous.Wait();
    }
    catch (System.AggregateException ae) {
        // Do what you will
    }
});

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 2016-11-25
    • 2013-11-26
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多