[英]How to call a web service method in c#
我想知道如何安全地調用WCF Web服務方法。 這兩種方法都可接受/等同嗎? 有沒有更好的辦法?
第一種方式:
public Thing GetThing()
{
using (var client = new WebServicesClient())
{
var thing = client.GetThing();
return thing;
}
}
第二種方式:
public Thing GetThing()
{
WebServicesClient client = null;
try
{
client = new WebServicesClient();
var thing = client.GetThing();
return thing;
}
finally
{
if (client != null)
{
client.Close();
}
}
}
我想確保客戶端正確關閉並處理掉。
謝謝
建議不要使用using
(無雙關語),因為即使是Dispose()
也會拋出異常。
這是我們使用的幾種擴展方法:
using System;
using System.ServiceModel;
public static class CommunicationObjectExtensions
{
public static void SafeClose(this ICommunicationObject communicationObject)
{
if(communicationObject.State != CommunicationState.Opened)
return;
try
{
communicationObject.Close();
}
catch(CommunicationException ex)
{
communicationObject.Abort();
}
catch(TimeoutException ex)
{
communicationObject.Abort();
}
catch(Exception ex)
{
communicationObject.Abort();
throw;
}
}
public static TResult SafeExecute<TServiceClient, TResult>(this TServiceClient communicationObject,
Func<TServiceClient, TResult> serviceAction)
where TServiceClient : ICommunicationObject
{
try
{
var result = serviceAction.Invoke(communicationObject);
return result;
} // try
finally
{
communicationObject.SafeClose();
} // finally
}
}
有了這兩個:
var client = new WebServicesClient();
return client.SafeExecute(c => c.GetThing());
第二種方法稍微好一點,因為您正在處理可能引發異常的事實。 如果你陷入困境並且至少記錄了特定的異常,那就更好了。
但是,此代碼將阻止,直到GetThing
返回。 如果這是一個快速操作,那么它可能不是一個問題,但另一種更好的方法是創建一個異步方法來獲取數據。 這會引發一個事件以指示完成,並且您訂閱該事件以更新UI(或者您需要做什么)。
不完全的:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.