强制一个OleDbConnection释放文件句柄 [英] Force an OleDbConnection to Release a File Handle

查看:438
本文介绍了强制一个OleDbConnection释放文件句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

<一个href="http://stackoverflow.com/questions/2862009/accessing-an-excel-file-throws-oledbexception-but-keeps-handle-on-file">Related问

我的code不释放,即使我打电话处置已初始化OleDbException的文件处理。有没有办法来明确强制程序释放文件句柄?

解决方案

在默认情况下,.NET数据库连接使用的。呼叫关闭()的Dispose()刚刚释放连接放回池中,它实际上并没有强求,关闭。它最终将超时池,居然被关闭。

在一些调查,似乎有两种主要方式得到它接近predictably:

  1. 禁用集中在连接字符串中 - 尝试添加​​的 OLE DB服务= -2; ,这应该给你所有的服务,除了汇集
  2. 尝试尽量使用<一href="http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection.releaseobjectpool.aspx"相对=nofollow> OleDBConnection.ReleaseObjectPool()

有关,你可能需要用超时打后一种方法 - 摘自链接的MSDN文章:

  

注意,单独调用该方法实际上不释放存在于池的活动连接。

     

必须执行以下操作的池最终处理之前:

     
      
  1. 调用Close连接对象返回到池中。
  2.   
  3. 允许每个连接对象超时池。
  4.   
  5. 呼叫ReleaseObjectPool。
  6.   
  7. 在调用垃圾收集器。
  8.   

我有一个用例为这个工作,一些内部软件需要与一块旧的,不灵活,片状和绝对重要专用软件进行交互。它需要打开一个共享的MDB数据库文件尽可能短的时间,尽量减少在那里的其他软件可能会提出异议(一个非常糟糕的事情)的窗口。

我打算使用连接字符串的方法,因为它看起来是简单的,以保证关闭和我的软件并没有真正从池中受益。

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?

解决方案

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.

这篇关于强制一个OleDbConnection释放文件句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆