本文將詳細介紹釋放客戶端資源(其中包括端口
微軟推薦的最佳實踐是拋棄using語句
var myClient = new MyClient();
try
{
//其他代碼
myClient
}
catch (CommunicationException)
{
myClient
}
catch (TimeoutException)
{
myClient
}
catch (Exception)
{
myClient
throw;
}
在最後增加對Exception異常的捕獲很有必要
以下是Steve Smith的擴展方法代碼
public static class Extensions
{
public static void CloseConnection(this ICommunicationObject myServiceClient)
{
if (myServiceClient
{
return;
}
try
{
myServiceClient
}
catch (CommunicationException ex)
{
Debug
myServiceClient
}
catch (TimeoutException ex)
{
Debug
myServiceClient
}
catch (Exception ex)
{
Debug
myServiceClient
throw;
}
}
}
利用該擴展方法
public class Util
{
public static void Using(T client
where T : ICommunicationObject
{
try
{
action(client);
client
}
catch (CommunicationException)
{
client
}
catch (TimeoutException)
{
client
}
catch (Exception)
{
client
throw;
}
}
}
使用時
Util
{
client
//其他代碼;
});
還有一種方法是定義一個自己的ChannelFactory
public class MyChannelFactory:IDisposable
{
private ChannelFactory m_innerFactory;
public MyChannelFactory(ChannelFactory factory)
{
m_innerFactory = factory;
}
~MyChannelFactory()
{
Dispose(false);
}
public void Close()
{
Close(TimeSpan
}
public void Close(TimeSpan span)
{
if (m_innerFactory != null)
{
if (m_innerFactory
{
return;
}
try
{
m_innerFactory
}
catch (CommunicationException)
{
m_innerFactory
}
catch (TimeOutException)
{
m_innerFactory
}
catch (Exception)
{
m_innerFactory
throw;
}
}
}
private void Dispose(booling disposing)
{
if (disposing)
{
Close();
}
}
void IDisposable
{
Dispose(true);
GC
}
}
其實采用代理模式的方式與此實現相同
From:http://tw.wingwit.com/Article/program/net/201311/13580.html