通常情況下我們關閉一個WCF鏈接都是簡單地寫把ICommunicationObject.Close()方法,但是這個方法有個問題就是當調用發生異常時,Close()會發生次生的異常,導致鏈接不能正常關閉。如果當這種異常很多時,必然對系統的穩定性有很大的影響,所以我們必須要考慮異常發生后如何關閉鏈接的問題。
我們可以寫一個擴展來專門關閉WCF鏈接,而不是使用原來的Close
????????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;
????????????}
????????}
????????{
????????????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;
????????????}
????????}
然后可以使用這個擴展:
????????protected?void?Close(T?client)
????????{
????????????if?(client?!=?null)
????????????{
????????????????IChannel?iChannel?=?client?as?IChannel;
????????????????if?(iChannel?!=?null)
????????????????????iChannel.CloseConnection();
????????????????else
????????????????{
????????????????????IDisposable?iDisposable?=?client?as?IDisposable;
????????????????????if?(iDisposable?!=?null)?iDisposable.Dispose();
????????????????}
????????????}
????????}
????????{
????????????if?(client?!=?null)
????????????{
????????????????IChannel?iChannel?=?client?as?IChannel;
????????????????if?(iChannel?!=?null)
????????????????????iChannel.CloseConnection();
????????????????else
????????????????{
????????????????????IDisposable?iDisposable?=?client?as?IDisposable;
????????????????????if?(iDisposable?!=?null)?iDisposable.Dispose();
????????????????}
????????????}
????????}
?
?
?