如何保存CLOSE事件后删除文件?
问题描述:
我有一个程序,它将单词文档存储在数据库中,并且它们被用户反复打开,关闭,然后保存回数据库。 打开时,我将它们放在临时文件夹中。 但关闭时,我想保存回数据库,然后直接删除它。如何保存CLOSE事件后删除文件?
我尝试这样做:
...
((DocumentEvents_Event)document).Close += DocumentClose;
...
delegate void MethodDelegate();
private void DocumentClose()
{
new MethodDelegate(deleteLater)();
}
void deleteLater()
{
//document.Close();
Thread.Sleep(1000);
File.Delete(this.tempDocFilePath);
}
但这不工作,我得到一个错误信息,告诉我该文件已经打开。 当我取消注释“document.Close();”接下来的两行都没有执行
有什么想法?
答
此代码可能受到竞争条件的限制。永远不要相信睡眠解决方案。等待特定的事件或轮询,然后采取行动。
答
好的我解决了!
这里是我的代码snippent:
private static Thread oThread = new Thread(new ParameterizedThreadStart(delete));
...
((DocumentEvents_Event)document).Close += DocumentClose;
...
private static void DocumentClose()
{
oThread.Start(path);
}
static void delete(object path)
{
try
{
File.Delete((string)path);
}
catch (Exception)
{
Thread.Sleep(500);
delete(path);
}
}
你是如何打开的文件吗? – 2011-01-28 20:17:03
该文件必须关闭,以便您可以删除该文件。找出它在Close()调用中崩溃的原因,删除任何try/catch语句。 – 2011-01-29 08:54:37