Force an OleDbConnection to Release a File Handle

故事扮演 提交于 2020-01-02 07:00:28

问题


Related Question

My code doesn't release a file handle even after I call dispose to an initialized OleDbException. Is there a way to explicitly force the program to release a file handle?


回答1:


By default, .NET database connections use pooling. Calling Close() and Dispose() just releases the connection back into the pool, it doesn't actually force it to close. Eventually it will time out of the pool, and actually be closed.

After a bit of research, there seem to be two main ways to get it close predictably:

  1. Disable pooling in the connection string - try adding OLE DB Services = -2;, which should give you all services except pooling
  2. Try to make use of OleDBConnection.ReleaseObjectPool()

For the latter approach you might need to play with timeouts - excerpt from the linked MSDN article:

Note that calling the method alone does not actually release the active connections that exist in the pool.

The following must occur before the pool is finally disposed:

  1. Call Close to return the connection object to the pool.
  2. Allow each connection object to time out of the pool.
  3. Call ReleaseObjectPool.
  4. Invoke garbage collection.

I have a use-case for this at work, where some in-house software needs to interact with piece of old, inflexible, flaky and absolutely critical proprietary software. It needs to open a shared MDB database file for as short a time as possible to minimise the window where the other software might "take issue" (a Very Bad Thing).

I'm planning on using the connection string approach, as it looks to be simpler to guarantee the close, and my software doesn't really benefit from the pool.




回答2:


Not sure why your code doesn't close a handle after calling Dispose(), since that calls Close() behind the scenes, but the following may help you write the code in a manner seen commonly:

using (OleDbConnection conn = new OleDbConnection(connString))
{
    //your stuff here
    conn.Close();  //not necessary, but doesn't hurt
}

This will close your handle regardless of whether an exception was thrown or not. Using blocks will Close/Dispose resources at the end of the block.



来源:https://stackoverflow.com/questions/2862232/force-an-oledbconnection-to-release-a-file-handle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!