No, the standard FileStream is not thread-safe.
You should use var safe = Stream.Synchronized(File.Open(...));
to create a thread-safe wrapper.
Pergunta
Is it safe to open a file and write a stream to it across multiple threads? If no what could I implement to make it safe?
Solução
No, the standard FileStream is not thread-safe.
You should use var safe = Stream.Synchronized(File.Open(...));
to create a thread-safe wrapper.
Outras dicas
No; it isn't safe by itself, but you can use the lock
keyword to control cross-thread access to the FileStream object.
For instance:
FileStream fStream = File.Open('foo.txt', FileMode.Append);
lock (fStream)
{
// Some operation on fStream
}
The answer posted by Knaģis may be the way to go in this instance, but mutex locking with the lock
keyword is a more general solution.
No. This is not thread safe. Intuitively, how does one write to a file when the index is a moving target? One idea is to create separate files and combine them with another process, possibly triggered by a completed event of some kind (e.g. all files arrived).
The concept of writing to a single file with multiple threads has some code smell. IMO, re-examine your options and come up with a different way of approaching this problem.