[英]Proper Error Handling on a WCF service call
我想找出最好的方法來調用WCF服務,並在發生錯誤或超時時進行處理。 這是我在做什么:
我有一個這樣的數據服務接口:
public interface IDataService
{void GetUserId(字符串userName,字符串密碼,操作getUserIdComplete); }
我這樣實現:
public class MockDataService : IDataService
{
private Action<string> _getUserIdCompleted;
private 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);
}
}
我的問題是,當發生錯誤或請求超時時,應用程序將終止。 我可以在電話周圍包裹一個try catch塊,但這聽起來是個壞主意。
有人可以幫我用這種方法優雅地處理超時和錯誤嗎?
據我所知,捕獲超時異常是處理它的唯一方法。
我更喜歡使用其他異步模式,因為它在處理異常方面具有更大的靈活性。 我會這樣。
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);
}
}
以我的拙見,后台線程的回調(任何由異步執行產生的回調)都應始終包裝在異常處理程序中。 后台線程中未處理的異常會殺死您的進程。
現在,這並不意味着您應該捕獲該異常並忽略它:)只是您應該正確處理它,無論這對您的應用程序意味着什么。 對於將要記錄它們的某些應用程序。 對於其他人,它將在某處更新某些狀態。 對於其他人,它可能會警告用戶錯誤。 或它們的組合:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.