Reputation: 106
I have a program that stores word documents in a database, and they are repeatedly opened, closed by the user and then saved back to the database. when opening I place them on a temp folder. but when closed, I want to save is back to the database and then delete it directly.
I tried this:
...
((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);
}
but this don't work, and I get an error message telling me the file is already opened. and when I uncomment "document.Close();" the next two lines are not excuted
any Ideas ?
Upvotes: 1
Views: 2704
Reputation: 106
Okay I solved it !
here's my code 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);
}
}
Upvotes: 0
Reputation: 50682
This code is possibly subject to a race condition. NEVER trust a Sleep-solution. Wait for a specific event or poll and then take action.
Upvotes: 1