问题
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:
- Disable pooling in the connection string - try adding OLE DB Services = -2;, which should give you all services except pooling
- 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:
- Call Close to return the connection object to the pool.
- Allow each connection object to time out of the pool.
- Call ReleaseObjectPool.
- 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