Zafar
Zafar

Reputation: 147

File Access in Windows Service

I have a Windows Service which has 8 timers running parallel (elapsed time = 10 sec) and each timer is performing some activity and logs the write_time when it enters the timer and end_time when it exits the timer and this happens for all the timers. I have a ASP.net application which reads the logs for the write_time and end_time for each timer and displays it on a grid.

Commonly I get an error for file operations which causes my timer to stop. The code block is below.

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

I get maximun times the exception The process cannot access the file. Please advise how to get rid of it.

Upvotes: 0

Views: 773

Answers (1)

ta.speot.is
ta.speot.is

Reputation: 27214

Most likely two or more threads are trying to write to the same file at the same time.

Create an instance of an object somewhere in your class and lock it whenever you need to write to the file.

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
    }
  }

  // ...

}

It would also be wise to wrap the StreamWriter in a using statement.

Upvotes: 2

Related Questions