2010-11-16 59 views
0

我想找出调用WCF服务并处理错误或超时时的最佳方法。下面是我在做什么:正确的错误处理WCF服务调用

我有一个这样的数据服务接口:

public interface IDataService 

{ 无效GetUserId(用户名字符串,字符串密码,操作getUserIdComplete); }

我实现它是这样的:

public class MockDataService : IDataService 
{ 
    private Action<string> _getUserIdCompleted; 
    privaet SomeServiceClient; 

    public MockDataService() 
    { 
     _proxy = new SomeServiceClient(); 
    } 

    public void GetUserId(string userName, string password, Action<int> getUserIdComplete) 
    { 
     _getUserComplete = getUserIdComplete; 

     var request = new UserRequest(); 
     request.UserName = userName; 
     request.Password = password; 
     //populate any other request info 

     _proxy.GetUserIdCompleted += new EventHandler<GetUserCompletedEventArgs>(_proxy_GetUserIdCompleted); 
     _proxy.GetUserIdAsync(request); 
    } 

    void _proxy_GetUserIdCompleted(object sender, GetUserIdCompletedEventArgs e) 
    { 
     _proxy.GetUserIdCompleted -= new EventHandler<GetUserCompletedEventArgs>(_proxy_GetUserIdCompleted); 
     _getUserIdComplete(e.UserId); 
    } 
} 

我的问题是,当错误发生或请求timesout,我弹的应用。我可以围绕这个调用包装一个try catch块,但这听起来像个坏主意。有人可以帮助我用这种方法优雅地处理超时和错误吗?谢谢!

回答

2

据我所知,捕获超时异常是处理它的唯一方法。

我更喜欢使用其他异步模式,因为它在处理异常时有更大的灵活性。我会去这样的。

public class MockDataService : IDataService 
{ 
    private SomeServiceChannel _channel; 

    public MockDataService() 
    { 
     var channelFactory = new ChannelFactory<SomeServiceChannel>(
        "CustomBinding_SomeService"); 
     _channel = channelFactory.CreateChannel(); 
     //to increase the timeout 
     _channel.OperationTimeout = TimeSpan.FromMinutes(5); 
    } 

    public void GetUserId(string userName, string password, Action<int> getUserIdComplete) 
    { 
     var request = new UserRequest(); 
     request.UserName = userName; 
     request.Password = password; 
     //populate any other request info 

     _proxy.GetUserIdCompleted += new EventHandler<GetUserCompletedEventArgs>(_proxy_GetUserIdCompleted); 
     _proxy.GetUserIdAsync(request); 
     _channel.BeginGetUserId(request, (iar) => 
      { 
       try 
       { 
        var result = _channel.EndGetUserId(iar); 
        getUserIdComplete(result.UserId); 
       } 
       catch (Exception ex) 
       { 
        //handle the exception 
       } 
      }, null); 
    } 

} 
+0

哇,我很喜欢这个!感谢您的建议。我会试试这个。我没有看到太多好的异步模式,但我确实喜欢这个。 – adminJaxon 2010-11-17 17:07:31

1

在我的非常愚蠢的观点,回调后台线程(任何异步执行的结果)应该总是包装在一个异常处理程序。未处理的异常在后台线程杀死你的进程。

现在,这并不意味着你应该捕获异常并忽略它:)只是你应该正确处理它,无论对于你的应用程序意味着什么。对于某些将要记录它们的应用程序。对于其他人来说,它会在某处更新某种状态。对于其他人可能会提醒用户错误。或者他们的组合:)

+0

谢谢tomasr! – adminJaxon 2010-11-17 17:08:06