• 你正确关闭WCF链接了吗?


    通常情况下我们关闭一个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;
                }
            }

    然后可以使用这个扩展:

            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();
                    }
                }
            }

  • 相关阅读:
    吴恩达 机器学习EX1学习笔记 MATLAB实现
    二分法解具有单调性的方程
    利用new定位运算符进行高效的数组动态增扩
    单循环链表基本操作及部分可能出现的细节问题
    数组中某元素的删除
    C# 实现可克隆(ICloneable)的类型
    Python学习十三
    Python学习十二
    Python学习十一
    Python学习十
  • 原文地址:https://www.cnblogs.com/chenjunbiao/p/1760320.html
Copyright © 2020-2023  润新知