2012-04-02 83 views
0

我有一個Windows服務,它有8個計時器並行運行(耗費時間= 10秒),每個計時器正在執行一些活動,並在進入計時器時記錄write_time,並在退出計時器時記錄end_time,這發生在所有的定時器上。 我有一個ASP.net應用程序,它爲每個計時器讀取write_timeend_time的日誌,並將其顯示在網格上。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"); 
     } 

我得到maximun倍以外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 
    } 
    } 

    // ... 

} 

這也將是明智的包裹StreamWriterusing聲明。