开发者

File being used by another process. Reason, and solution?

The process cannot access the file 'abc.log' because it is being used by another process.

Hi, I've seen this exception from my application occationaly but I am still trying to fix that, hope I will get some insight from stackoverflow.

In my application I've have defined a WriteToLog function which will write to a log file. Also the mainForm of my application will launch a backgroundWorker do some job which also calls the WriteToLog. Maybe two threads access a file will cause a problem? But in my code I 've already do my best to write flush and close the text file (I think), and here is my code from WriteToLog:

 StreamWriter sw = null;
 string newText = "";
 try
 {
     //populate the content for newText
     sw = File.AppendText(LOG_FILE);
     sw.Write(newText);
     sw.Flush();
     sw.Close();
 }
 catch (IOException ex)
 {
     MessageBox.Show("Failed to write to log!\n\t" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
 finally
 {
     if (sw != null)
     {
         sw.Close();
     }
 }

I think as long as I flush and close the streamWriter, I should be able call the WriteToLog multi-times and in multi-threads isn't it? Or if I am wrong, could I simple make the file open shar开发者_StackOverflow社区ed, or there are other reason/solutions?


No; different threads attempting to open the file at the same time will interfere with each other. You could lock a shared object to force the threads to run one at a time.

Or just use the built-in .NET tracing functionality; you can configure your app.config to write to a file.


This is probably unrelated to your problem, but you can simplify this code a bit by using a using statement with your StreamWriter instead of having the finally. This also has the added benefit of not having to explicitly call Close or Flush (closing the stream flushes it, too).

I haven't tried compiling this, but it should be something like:

string newText = "";
try
{
    //populate the content for newText
    using (StreamWriter sw = File.AppendText(LOG_FILE))
    {
        sw.Write(newText);
    }
}
catch (IOException ex)
{
    MessageBox.Show("Failed to write to log!\n\t" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}


If you are calling this from multiple threads, you have to ensure that the file operations are atomic. It's very likely that Thread A gets past the AppendText and stops e.g. on Write, at which point Thread B gets scheduled and starts writing the same (now locked) file.

One way to handle this is to place a lock region around the statements presented in your code sample.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜