2012-03-23 4 views
1

여러 .NET 프로세스에서 텍스트 파일을 수정해야합니다. 나는 여러 프로세스를 시작하는 C# GUI 응용 프로그램을 사용하여 숫자를 계산합니다. 이들은 몇 밀리 초마다 같은 텍스트 파일에 줄을 추가해야합니다. 마스터 프로세스는 파일의 크기를 모니터링하고 임계 값에 도달하면 파일을 업로드하고 삭제합니다..NET에서 파일 잠그기

이 현재 코딩 방법, 존재하지 않는 경우 텍스트 파일을 만들 추가,하지만 그 변화하기 쉬운 것입니다 처리합니다.

어떻게 구현할 수 있습니까?

+1

[FileShare'] (http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx) 값을 전달하는 것은 무엇입니까? – ildjarn

+3

신뢰할 수있는 방식으로 시도한 것을 알려 주시면 시작할 수 있습니다. –

+0

당신이 성취하려는 것을 말하기는 어렵습니다. 파일 시스템 세마포어를 실험하고 있다면 소스를보고 잘못된 것을 확인하는 것이 좋습니다. 괜찮은 솔루션이 필요한 경우 메시지 대기열을 폴링하고 스레드 안전성이있는 쓰기를 수행하는 싱글 톤 만 있으면됩니다. 좋은 예가 http://nlog-project.org/wiki/Tutorial – bytebuster

답변

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(); 
    } 
}