0

I have coded a UI import tool that will scan a bunch of folders, locate all XML files in them, load them to do a first basic check on validity, then try to import them in the DB (which causes another even bigger bunch of validity checks to run). When the basic checks or the import fails, the app shows a detailed error message to the user, so the user can open up the respective XML file and edit it. BUT... the user CANNOT save the file, because the file "is in use by another process".

At that stage, all my importer objects are long gone, but I figured they might not be garbage collected yet, so they keep open handles to the XML files. So I tried a GC.Collect() after the checking/import process and then magically the user can edit and save the XML files.

All my code ever does with the XML files is this:

XmlReader reader = XmlReader.Create(m_xmlInputFile);
m_XmlDocument = new XmlDocument();
m_XmlDocument.Load(reader);

'reader' is a local variable, so it goes out of scope immediately, m_XmlDocument is a member variable that will live as long as the importer object is alive. The importer object is a local variable in another function, so everything should end up in death row after all is said and done. Still it looks like waiting on death row might take a while...

Not that it matters much in my case, but just out of curiosity I would like to know if there is something I could do (apart from forcing a GC) to "free" the XML files on disk, so that the user can do his/her editing without surprises.

Thanks

4

1 回答 1

1

XmlReaderimplements IDisposable,并且您没有推迟合同的结束。

Dispose在适当的时候调用它,或者(更好地)将使用它的代码包围在一个using块中:

using(XmlReader reader = XmlReader.Create(m_xmlInputFile))
{
    m_XmlDocument = new XmlDocument();
    m_XmlDocument.Load(reader);
}

如果您发现自己强制进行垃圾收集,那么您做错了什么(在 99.99% 以内)。

当引用超出范围时不会发生任何神奇的事情 - 是的,它所引用的对象将有资格进行垃圾回收(如果这是对该对象的最后一个剩余引用),但不会运行额外的代码。

然而,如果对象持有资源,并且应该尽快清理,它将实现一次性模式

于 2012-06-07T09:04:59.587 回答