2011-01-28 94 views
1

我有一個程序,它將單詞文檔存儲在數據庫中,並且它們被用戶反覆打開,關閉,然後保存回數據庫。 打開時,我將它們放在臨時文件夾中。 但關閉時,我想保存回數據庫,然後直接刪除它。如何保存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();」接下來的兩行都沒有執行

有什麼想法?

+0

你是如何打開的文件嗎? – 2011-01-28 20:17:03

+0

該文件必須關閉,以便您可以刪除該文件。找出它在Close()調用中崩潰的原因,刪除任何try/catch語句。 – 2011-01-29 08:54:37

回答

1

此代碼可能受到競爭條件的限制。永遠不要相信睡眠解決方案。等待特定的事件或輪詢,然後採取行動。

0

好的我解決了!

這裏是我的代碼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); 
    } 
}