如何关闭 InterSystems.Data.CacheClient.dll 数据库连接?

How do I close a InterSystems.Data.CacheClient.dll database connection?

我与 Caché 的连接在整个应用\IIS 完成后才会关闭。

例如,创建一个引用 InterSystems.Data.CacheClient.dll 的新项目 并尝试以下操作:

static void Main(string[] args)
{
    var connection = new CacheConnection("SERVER=10.10.10.41;PORT=1972;DATABASE=dsa-som-ting;PROTOCOL=TCP;UID=user;PWD=password;");

    connection.Open();      
    Console.ReadKey();  //open

    connection.Close();     
    Console.ReadKey(); //still open!

    connection.Dispose();       
    Console.ReadKey(); //still open!
}

连接始终保持打开状态,正如我在 Caché 门户中看到的那样:

如何关闭连接??

.NET 使用连接池在应用程序结束前默认保持最多 100 个连接打开。

因此,即使您调用 connection.Close(),并且它在您的应用程序中显示为关闭,.NET 仍会保留它的副本以供稍后调用 connection.Open() 时使用,以节省时间.

要更改池的大小,请使用如下连接字符串:

new CacheConnection("SERVER=10.10.10.41;PORT=1972;DATABASE=dsa-clb-def;PROTOCOL=TCP;UID=_System;PWD=sys;Max Pool Size=50;");

另一种选择是创建一个实现 IDisposable 接口的自定义 class。这有助于 GC 并允许您更轻松地关闭连接。

class CustomCacheConnection : IDisposable
{
    private static string connString;

    private static CacheConnection conn;
    private static CacheCommand cmd;

    public CustomCacheConnection(string sql)
    {
        conn = new CacheConnection();
        connString = GetConnectionString();
        cmd = new CacheCommand(sql, conn);
    }

    #region IDisposable Support
    private bool disposed = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                cmd.Dispose();

                //make sure the connection state is open so we can close it
                if (conn != null && conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            disposed = true;
        }
    }

    // This code added to correctly implement the disposable pattern.
    public void Dispose()
    {
        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
    }
    #endregion
}

然后在您的 Main()

var sql = "SELECT * FROM Sample.Person";

using (CustomCacheConnection connection = new CustomCacheConnection(sql))
{
     //do stuff
}