2012-04-02 15 views
0

私は、8つのタイマーが並列実行(経過時間= 10秒)し、各タイマーが何らかのアクティビティーを実行し、タイマーに入ったときにwrite_timeを記録し、タイマーを終了したときにend_timeこれはすべてのタイマーで発生します。 私は、各タイマーのwrite_timeend_timeのログを読み取り、グリッドに表示するASP.netアプリケーションを持っています。Windowsサービスでのファイルアクセス

一般的に私のタイマーを停止させるファイル操作にエラーが発生します。コードブロックは以下の通りです。

Write_time

 FileInfo file = null; 
     StreamWriter write = null; 
     try 
     { 
      file = new FileInfo(ConfigurationManager.AppSettings["SupportFilePath"].ToString() + processName + "_Log.txt"); 

      write = new StreamWriter(file.FullName); 
      write.Write(string.Empty); 

      write.Write(processName + "_" + time + " at: _" + System.DateTime.Now.ToString()); 
      write.Close(); 
      write.Dispose(); 

     } 
     catch (System.Exception ex) 
     { 
      _errorMonitoringEngine.ErrorInfo(" ", ex.StackTrace.ToString(), ex.Message, "Email Notification Engine", "WriteTimeProcess2"); 
     } 

私がする最大の回例外The process cannot access the fileを取得します。それを取り除く方法をアドバイスしてください。

答えて

2

ほとんどの場合、複数のスレッドが同じファイルに同時に書き込みを試みている可能性があります。

クラスのどこかにobjectのインスタンスを作成し、ファイルに書き込む必要があるときはいつでもlockのインスタンスを作成します。

public class Example 
{ 

    // ... 

    // Depending on whether there are one or many instances of 
    // this class determines whether this needs to be static 
    // or not. If it needs to be static, use a static constructor. 
    private object syncObject = new object(); 

    // ... 

    void WriteToFile() 
    { 
    lock (syncObject) 
    { 
     // Do file IO 
     // Now no two threads will attempt to access the file at the same time 
    } 
    } 

    // ... 

} 

またusing文でStreamWriterをラップするのが賢明だろう。

関連する問題