Writing to a File from Multiple Threads.
I have a program that writes to a file from several different threads. How do you synchronize the file or do whatever to make writing to the files thread safe. I am currently using FileStream and StreamWriter for my IO operations.
gordonPosted Dec 13, 2007, 6:21 AM
Posted Dec 12, 2007, 7:21 PM
You can do anything you want to with the FileStream within the lock code block, locking it doesnt actually affect the way the FileStream object works.
gordonPosted Dec 12, 2007, 7:08 PM
So I need to reopen the filestream each time I want to write to it then lock it then close it when I complete the write?
Posted Dec 12, 2007, 2:22 PM
That way, other threads that are trying to access it will have to wait until it becomes unlocked in order to use it.
Ex:
FileStream fileStream = new
FileStream("myfile.txt", FileMode.Open, FileAccess.Write);
//Lock the stream object to prevent
//use by other threads until it is unlocked.
lock (fileStream)
{
//Perform some operations on the
//stream and make sure to close it.
}
//The stream is now unlocked and able to
//be used by another thread.
Just make sure that you always unlock the stream regardless of an error or not. A thread that is trying to access a locked resource will block (wait) until that resource becomes unlocked. If you dont unlock it, you may get something called "threadlock" which causes all of the threads attempting to access the resource to simple stall indefinitely because the resource never gets unlocked.