通过等待任务或访问其Exception属性,未观察到任务的异常

Mon*_*RPG 4 c# wpf error-handling exception task

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

通过等待任务或访问其Exception属性,未观察到任务的异常.结果,终结器线程重新抛出了未观察到的异常.

    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();
Run Code Online (Sandbox Code Playgroud)

Rik*_*iko 6

你没有处理任何异常.

改变这一行:

InsertMainLinks.Wait();
Run Code Online (Sandbox Code Playgroud)

至:

try { 
    InsertMainLinks.Wait(); 
}
catch (AggregateException ae) { 
    /* Do what you will */ 
}
Run Code Online (Sandbox Code Playgroud)

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

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

例如:

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
});
Run Code Online (Sandbox Code Playgroud)

要么

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
    }
});
Run Code Online (Sandbox Code Playgroud)