2010-10-17 110 views
0

我在.NET 4.0中創建任務時遇到了一個奇怪的例外。在.net 4.0上處理任務異常

我越來越與全球Updomain未處理的異常處理程序窗口服務異常,所以我沒有確切的堆棧:A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property.

我認爲它發生在下面的代碼段:

for (int i = 0; i < _workers.Length; ++i) 
     { 
      int j = i; // copy 

      Task t1 = Task.Factory.StartNew(() => 
      { 
       try 
       { 
        if (!_workers[j].Join(4000)) 
         LogWriter.Trace("Failed to join thread", "ThreadFailureOnDispose"); 
       } 
       catch (Exception ex) 
       { 
        OnLogged(ex.Message + ex.StackTrace); 
       } 
      }); 

     } 

有人有想法嗎?它是否具有聚合異常功能?

+0

有關於此的一些相當不錯的信息:http://social.msdn.microsoft.com/Forums/en-US/rx/thread/ee5dba5d-eea9-4d85-8f58-c2e1c71ef33a – 2010-10-17 15:12:43

+0

第一次修復您的UnhandledException事件處理程序。 _workers任務也是如此嗎? – 2010-10-17 15:15:14

+0

沒有。 _工人是線程。你是什​​麼意思解決我的UnhandledException事件處理程序?從某種原因Windows服務停止,儘管執行被捕獲並記錄在AppDomain.CurrentDomain.UnhandledException。 – user437631 2010-10-17 16:23:09

回答

0

好,我覺得任務應該抓住AggregateExecption使用的Parallel.For \的foreach時如下:

try 
     { 
      Parallel.For(0, _workers.Length, i => 
      { 

       DoWork(i); 

      }); 

     } 
     catch (AggregateException ex) 
     { 
      // Assume we know what's going on with this particular exception. 
      // Rethrow anything else. AggregateException.Handle provides 
      // another way to express this. See later example. 
      foreach (var e in ex.InnerExceptions) 
      { 
       OnLogged(e.Message + e.StackTrace); 
      } 

     } 
0

你應該找到的例外是AggregateException型(供將來參考提問的時候包括異常類型—是關鍵信息)。

這包括在其InnerExceptions屬性中拋出的異常。

+0

我該怎麼做?任何例子? – user437631 2010-10-17 16:23:45

+0

@ user437631爲了調試查看輸出,找出失敗並修復它。在運行時可以在任務中處理的運行時處理案例,或者異常的延續集。即至於任何例外情況。 – Richard 2010-10-18 06:55:13