2010-12-01 74 views
1

在Silverlight中,我使用lambdas從我的服務(本例中是WCF數據服務)中檢索數據。回調中的異常被系統吞噬,除非我用try catch來處理它們。例如:在Silverlight中處理異常異步lambda調用

this.Context.BeginSaveChanges(() => 
{ 
    // throwing an exception is lost and the Application_UnhandledException doesn't catch it 

}, null); 

我有一個輔助函數來記錄異常和重定向到一個ASPX一般錯誤頁面,後來我在嘗試/捕獲lambda表達式包一切是好的,如果我必須做它,但有沒有更好的辦法?

回答

2

您可以創建一組輔助方法來包裝拉姆達與: -

public static class Helper 
{ 
    public static AsyncCallback GetAsyncCallback(Action<IAsyncResult> inner) 
    { 
     return (a) => 
     { 
      try 
      { 
       inner(a); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
    } 

    public static Action GetAction(Action inner) 
     { 
     return() => 
     { 
      try 
      { 
       inner(); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
     } 

     public static Action<T> GetAction(Action<T> inner) 
     { 
     return (a) => 
     { 
      try 
      { 
       inner(a); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
     } 
     // and so on also:- 

     public static Func<T> GetFunc(Func<T> inner;) 
     { 
     return() => 
     { 
      try 
      { 
       return inner(); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
     } 
     public static Func<T1, TReturn> GetFunc(Func<T1, TReturn> inner;) 
     { 
     return (a) => 
     { 
      try 
      { 
       return inner(a); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
     } 
} 

現在你可以用拉姆達的,不用擔心默認樣板異常處理: -

this.Context.BeginSaveChanges(Helper.GetAsyncCallback((ar) =>    
{    
    // Only needs specific exception handling or none at all    

}), null);