即使在我对初始化的 OleDbException 调用 dispose 之后,我的代码也不会释放文件句柄。有没有办法显式强制程序释放文件句柄?
最佳答案
默认情况下,.NET 数据库连接使用 pooling 。调用 Close()
和 Dispose()
只是将连接释放回池中,实际上并不会强制它关闭。最终它会从池中超时,并且实际上被关闭。
经过一番研究,似乎有两种主要方法可以使其按预期接近:
- 在连接字符串中禁用池 - 尝试添加
OLE DB Services = -2;
,它应该为您提供除池化之外的所有服务 - 尝试利用
OleDBConnection.ReleaseObjectPool()
对于后一种方法,您可能需要使用超时 - 摘自链接的 MSDN 文章:
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.
我在工作中有一个这样的用例,其中一些内部软件需要与旧的、不灵活的、脆弱的和绝对关键专有软件进行交互。它需要在尽可能短的时间内打开共享 MDB 数据库文件,以最大限度地减少其他软件可能“出现问题”的窗口(这是一件非常糟糕的事情)。
我计划使用连接字符串方法,因为它看起来更容易保证关闭,而且我的软件并没有真正从池中受益。
关于.net - 强制 OleDbConnection 释放文件句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2862232/