[英]How to close a WCF Client connection
我是WCF的新手,到目前為止已經學習了。 但是我想知道如何從客戶端關閉WCF客戶端連接(如果需要的話?我想是)。
我有一個名為
[ServiceContract]
ICalculatorService { blabla... }
問題是在客戶端。 到目前為止,我使用以下格式:
EndpointAddress epAddress = new EndpointAddress("http://localhost:8090/CalculatorService");
ICalculatorService calculatorProxy = ChannelFactory<ICalculatorService>.CreateChannel(new WSHttpBinding(), epAddress);
現在我可以:
Result numeralResult = calculatorProxy.AddNumbers(4, 5);
我得到了結果,我很高興。
每按一次(例如)按一次按鈕,就會使上述代碼運行一次。
我的問題是:效率高嗎?
現在,我正在考慮將其放入一個單獨的類中,例如:
class CalculatorProxy
{
static EndpointAddress epAddress = new EndpointAddress("http://localhost:8090/CalculatorService");
public static ChannelFactory<ICalculatorService> GetCalculatorProxy()
{
}
public void Dispose() { ... }
}
...並像這樣使用它:
using (ICalculatorService calculatorClient = CalculatorProxy.GetCalculatorProxy())
{
calculatorClient.AddNumbers(4, 4);
}
哪一個會更有效?
更新:
謝謝大家的答案。
我終於結束了這堂課:
class CalculatorServiceClient : ClientBase<ICalculatorService>, IDisposable
{
static EndpointAddress epAddress = new EndpointAddress("http://localhost:8090/CalculatorService");
ICalculatorService myCalculatorProxy;
public CalculatorServiceClient()
: base(new WSHttpBinding(), epAddress)
{
myCalculatorProxy = ChannelFactory.CreateChannel();
}
public static CalculatorServiceClient GetNewInstance()
{
return new CalculatorServiceClient();
}
public Result AddNumbers(int aIn, int bIn)
{
return myCalculatorProxy.AddNumbers(aIn, bIn);
}
public void Dispose()
{
try
{
Close();
}
catch (CommunicationObjectFaultedException ex)
{
throw new DBCommunicationException("CalculatorServiceClient is in the Faulted state.", ex);
}
catch (Exception ex)
{
throw new DBCommunicationException("Communication is unsuccessful between the CalculatorServiceClient and the CalculatorService.", ex);
}
}
}
並以這種方式使用它:
try
{
using (CalculatorServiceClient calculatorClient = CalculatorServiceClient.GetNewInstance())
{
Result aResult = calculatorClient.AddNUmbers(tbA.Text, tbB.Text);
}
}
catch (DBCommunicationException ex)
{
MessageBox.Show("Service is shut down.");
}
我的問題是:這樣有效嗎?
您只需在完成每個操作后關閉客戶端,就不再需要進行其他調用了。 工作完成后,只需使用Close
方法Close
客戶端:
calculatorProxy.Close();
關於Close()
方法,MSDN文檔指出:
此方法使CommunicationObject正常地從除Closed狀態以外的任何狀態轉換為Closed狀態。 使用Close方法可以在返回之前完成所有未完成的工作。 例如,完成所有緩沖消息的發送。
關於您的方法,我認為第二種方法很好而且效率更高,因為您還正在實現Dispose模式並釋放使用的資源(這取決於您使用的資源)。 只需在工作完成后添加Close()
方法即可:
calculatorClient.AddNumbers(4, 4);
calculatorProxy.Close();
還請記住,創建和連續關閉WCF客戶端沒有性能問題。 這只是正常習慣。
您可以調用代理類的close方法。
喜歡
calculatorProxy.Close();
或者,如果發生異常 ,則在服務代理類上調用abort方法。
try
{
calculatorProxy.SomeMethod();
calculatorProxy.Close();
}
catch
{
calculatorProxy.Abort();
}
請參閱此鏈接以獲取更多詳細信息
我認為您最好將所有這些都放在一個類中。 建立類的實例可以構造連接並在時間到時關閉/處置。 在此之前,您將有一個開放且活動的頻道可以撥打電話。
using (var client = new CalculatorServiceClient())
{
client.SomeMethod();
}
將對計算器Web服務的服務引用添加到客戶端項目后,CalculatorServiceClient對象將可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.