A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property

為{幸葍}努か 提交于 2019-12-09 13:30:12

问题


These are my tasks. How should i modify them to prevent this error. I checked the other similar threads but i am using wait and continue with. So how come this error happening?

A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.

    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();

回答1:


You're not handling any exception.

Change this line:

InsertMainLinks.Wait();

TO:

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

In general: to prevent the finalizer from re-throwing any unhandled exceptions originating in your worker thread, you can either:

Wait on the thread and catch System.AggregateException, or just read the exception property.

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
});

OR

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
    }
});


来源:https://stackoverflow.com/questions/9193548/a-tasks-exceptions-were-not-observed-either-by-waiting-on-the-task-or-accessi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!