关闭WCF链接正确方法详解

开发 开发工具
关闭WCF链接是在实际编程中比较重要的一个方法。在这里我们就为大家详细介绍一下有关关闭WCF链接的正确方法,方便大家学习。

WCF是一款由微软开发的有关通信的一个开发框架。它可以为我们创造一个可靠的,跨平台的方式。通常情况下我们关闭WCF链接都是简单地写把ICommunicationObject.Close()方法。#t#

但是这个方法有个问题就是当调用发生异常时,Close()会发生次生的异常,导致链接不能正常关闭。如果当这种异常很多时,必然对系统的稳定性有很大的影响,所以我们必须要考虑异常发生后如何关闭链接的问题。

我们可以写一个扩展来专门关闭WCF链接,而不是使用原来的Close

  1. public static void CloseConnection
    (this ICommunicationObject myServiceClient)  
  2. {  
  3. if (myServiceClient.State !=
     CommunicationState.Opened)  
  4. {  
  5. return;  
  6. }  
  7. try  
  8. {  
  9. myServiceClient.Close();  
  10. }  
  11. catch (CommunicationException ex)  
  12. {  
  13. Debug.Print(ex.ToString());  
  14. myServiceClient.Abort();  
  15. }  
  16. catch (TimeoutException ex)  
  17. {  
  18. Debug.Print(ex.ToString());  
  19. myServiceClient.Abort();  
  20. }  
  21. catch (Exception ex)  
  22. {  
  23. Debug.Print(ex.ToString());  
  24. myServiceClient.Abort();  
  25. throw;  
  26. }  

然后可以使用这个扩展来实现关闭WCF链接:

 

  1. protected void Close(T client)  
  2. {  
  3. if (client != null)  
  4. {  
  5. IChannel iChannel = client 
    as IChannel;  
  6. if (iChannel != null)  
  7. iChannel.CloseConnection();  
  8. else  
  9. {  
  10. IDisposable iDisposable =
     
    client as IDisposable;  
  11. if (iDisposable != null) 
    iDisposable.Dispose();  
  12. }  
  13. }  

 

责任编辑:曹凯 来源: 博客园
相关推荐

2010-02-26 11:22:16

LitwareHR使用

2010-02-24 10:35:56

WCF链接服务超时

2010-02-22 14:28:35

WCF实现loadin

2010-03-01 16:59:31

WCF异常调试

2010-02-26 09:33:18

WCF创建WebSer

2010-02-23 17:59:52

WSIT连接WCF

2010-02-25 16:07:28

WCF REST

2010-02-23 17:05:38

2010-03-01 10:26:40

WCF异步服务

2010-03-01 17:44:39

Silverlight

2010-02-26 11:15:51

WCF接口方法

2010-03-02 14:12:30

WCF枚举类型

2009-12-22 16:36:38

WCF重载

2010-02-25 16:52:12

引用WCF服务

2010-02-25 13:48:23

WCF动态创建代码

2010-02-25 09:13:34

WCF异步调用

2010-03-02 17:35:20

WCF服务加载

2010-02-23 14:48:38

WCF事件通知

2010-02-25 13:54:48

WCF安全参数

2010-02-23 10:51:32

WCF Address
点赞
收藏

51CTO技术栈公众号