2010-12-01 37 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);