Reputation: 21406
using (FileStream fs = File.Open(@"C:\logs\log1.txt",FileMode.Append,
FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter w = new StreamWriter(fs))
{
w.WriteLine(logMessage);
w.Flush();
isSuccessful = true;
}
}
In code above, I am instantiating a FileStream object so the file is opened in FileShare.ReadWrite mode.
My Question: Does this mean that the code that writes a line to the opened file is going to be thread-safe, Or FileShare.ReadWrite implies something other than thread-safe?
Upvotes: 0
Views: 748
Reputation: 171178
FileShare
has nothing to do with thread-safety. The values of FileAccess
and FileShare
are only used at the time the file is opened. They might lead to failure and they control the rights that you and others have.
Besides that, there is no change in behavior regarding what happens when multiple processes and threads are involved.
A single FileStream
instance is not thread-safe.
Upvotes: 1
Reputation: 37020
No, it just allows multiple processes to write to the file. You will still need to implement some locking mechanism on the File.Write operation if you want it to be thread safe.
Check out the answer to this question for more info: What is the fastest and safest way to append records to disk file in highly loaded .ashx http handler?
Upvotes: 1