2012-03-23 75 views
1

我需要修改多個.NET進程中的文本文件,我嘗試過的任何操作都不可靠。我有一個C#GUI應用程序,它啓動多個進程來執行一些數字運算。那些需要每隔幾毫秒向同一文本文件添加行的行。主進程監視文件的大小,一旦達到某個閾值,就會上傳並刪除它。在.NET中鎖定文件

這些目前編碼的方式,附加文本的過程創建文件,如果它不存在,但很容易改變。

我該如何執行此操作?

+1

哪個['FileShare'(http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx)值,你傳遞? – ildjarn 2012-03-23 00:49:39

+3

你可以先告訴我們你試過的東西不能可靠工作。 – 2012-03-23 00:56:56

+0

很難說出你想要完成什麼。 如果您只是試驗文件系統信號量,那麼很高興看到您的源代碼看到錯誤。 如果您需要一個體面的解決方案,也許您只需要一個輪詢消息隊列並執行線程安全寫入的單例。這是一個很好的例子http://nlog-project.org/wiki/Tutorial – bytebuster 2012-03-23 03:20:51

回答

0

該方法會反覆嘗試打開文件,直到可以寫入文件,在10ms後超時。

private static readonly TimeSpan timeoutPeriod = new TimeSpan(100000); // 10ms 
private const string filename = "Output.txt"; 

public void WriteData(string data) 
{ 
    StreamWriter writer = null; 
    DateTime timeout = DateTime.Now + timeoutPeriod; 
    try 
    { 
     do 
     { 
      try 
      { 
       // Try to open the file. 
       writer = new StreamWriter(filename); 
      } 
      catch (IOException) 
      { 
       // If this is taking too long, throw an exception. 
       if (DateTime.Now >= timeout) throw new TimeoutException(); 
       // Let other threads run so one of them can unlock the file. 
       Thread.Sleep(0); 
      } 
     } 
     while (writer == null); 
     writer.WriteLine(data); 
    } 
    finally 
    { 
     if (writer != null) writer.Dispose(); 
    } 
}