WCF中通過Dispose有效實現重用

來源:互聯網
上載者:User

本文將詳細介紹釋放用戶端資源(其中包括連接埠、通道)和關閉串連的問題。毫無疑問,在.NET Framework中,一個資源(尤其是非託管資源)通常都需要實現IDisposable介面。一旦實現了該介面,我 們就可以使用using語句來管理資源,這是最便捷的方式。但是,一旦在using語句中拋出了異常,就可能 不會正確完成資源的回收,尤其是串連,很可能會一直開啟,既佔用了通道和連接埠,還可能出現資源的浪 費,從而影響系統的效能和穩定性。

微軟推薦的最佳實務是拋棄using語句,轉而利用 try/catch(/finally)語句。它要求在try語句中調 用Close()方法,而在catch中調用Abort()方法。在新聞中已經說明了Close()與Abort()方法的區別,即 後者可以強制地關閉用戶端,包括關閉用戶端串連,釋放資源。由於Close()方法可能會拋出 CommunicationException和TimeoutException異常,通常的用戶端代碼應該是這樣:

var myClient = new MyClient();
try
{
//其他代碼
myClient.Close ();
}
catch (CommunicationException)
{
myClient.Abort();
}
catch  (TimeoutException)
{
myClient.Abort();
}
catch (Exception)
{
myClient.Abort();
throw;
}

在最後增加對Exception異常的捕獲很有必要,因為我們不知道Close()方法會否拋出某些不可預知的 異常,例如 OutOfMemoryException等。新聞中提到Steve Smith的方法其實就是對這段冗長代碼的封裝, 封裝方式是採用擴充方法,擴充的類型為ICommunicationObject。這是因為所有的用戶端對象都實現了 ICommunicationObject介面。

以下是Steve Smith的擴充方法代碼:

public static class Extensions
{
public static void CloseConnection (this ICommunicationObject myServiceClient)
{
if (myServiceClient.State !=  CommunicationState.Opened)
{
return;
} 
try
{
myServiceClient.Close ();
}
catch (CommunicationException ex)
{
Debug.Print(ex.ToString ());
myServiceClient.Abort();
}
catch (TimeoutException ex)
{
Debug.Print (ex.ToString());
myServiceClient.Abort();
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
myServiceClient.Abort();
throw;
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.