通过等待任务或访问其Exception属性,未观察到任务的exception
这些是我的任务。 我应该如何修改它们以防止此错误。 我检查了其他类似的线程,但我正在使用等待并继续。 那怎么会发生这个错误呢?
通过等待任务或访问其Exception属性,未观察到任务的exception。 结果,终结器线程重新抛出了未观察到的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();
你没有处理任何exception。
改变这一行:
InsertMainLinks.Wait();
至:
try { InsertMainLinks.Wait(); } catch (AggregateException ae) { /* Do what you will */ }
通常:为了防止终结器重新抛出源自您的工作线程的任何未处理的exception,您可以:
等待线程并捕获System.AggregateException,或者只读取exception属性。
例如:
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 } });