2012-03-23 76 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(); 
    } 
}