2009-02-10 30 views
6

併發的同事。來自後臺線程的陷阱異常

我需要能夠捕獲可能從後臺線程拋出的異常。

讓我們爲自己的代碼講(這是一個糟糕的代碼)

public delegate bool CheckForUpdatesHandler(Uri uri); 
    public class UpdatesChecker { 
     public event AsyncCompletedEventHandler CheckForUpdatesAsyncCompleted; 
     protected virtual void OnCheckForUpdatesAsyncCompleted(AsyncCompletedEventArgs args) { 
      if (CheckForUpdatesAsyncCompleted != null) 
       CheckForUpdatesAsyncCompleted(this, args); 
     } 

     public bool CheckForUpdates(Uri ftp) {    
      Thread.Sleep(1000); 
      throw new Exception("bla"); 
      return true; 
     }  


     public void CheckForUpdatesAsync(Uri ftp){    
      var action = new CheckForUpdatesHandler(CheckForUpdates); 
      var c=action.BeginInvoke(ftp, delegate(IAsyncResult state) { 
       OnCheckForUpdatesAsyncCompleted(new AsyncCompletedEventArgs(null, false, null)); 
      }, null); 
     }  
    } 

回答

8

隨着Delegate.BeginInvoke,異常會通過調用.EndInvoke檢索 - 你必須做的反正,以防止泄漏。

隨着BackgroundWorker的,它會出現在完成事件

在香草Thread,未處理的異常會推倒過程。

然而,最簡單的方法是:不要讓它扔...

public bool CheckForUpdates(Uri ftp) { 
     try { 
      Thread.Sleep(1000); 
      throw new Exception("bla"); 
      return true; 
     } catch (Exception ex) { 
      // raise an event, call a method/callback, do something 
     } 
    } 

如果您目前沒有使用EndInvoke,那麼也許切換到上面的圖案,只是直接使用ThreadPool(而比Delegate.BeginInvoke)。

+0

謝謝,馬克,你再次幫助我:-) – Valentin 2009-02-10 13:21:42