Windows 服务中的文件访问

本文关键字:文件 访问 服务 Windows | 更新日期: 2023-09-27 18:29:39

我有一个Windows服务,它有8个计时器并行运行(经过的时间= 10秒(,每个计时器都在执行一些活动,并在进入计时器时记录write_time,在退出计时器时记录end_time,所有计时器都会发生这种情况。我有一个 ASP.net 应用程序,它可以读取每个计时器的write_timeend_time的日志并将其显示在网格上。

通常,我会收到文件操作错误,导致计时器停止。代码块如下。

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.请告知如何摆脱它。

Windows 服务中的文件访问

很可能有两个或多个线程同时尝试写入同一个文件。

类中的某个位置创建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
    }
  }
  // ...
}

StreamWriter包装在using语句中也是明智的。