Skip to content

Writing to a File from Multiple Threads.

gordon

Asked Dec 12, 2007, 9:19 AM EST4 answers
Share
LinkedInX
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.

4 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Have you tried making the FileStream a shared resource among the threads and locking the FileStream object whenever a thread is using it?

    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.
    0
  • 0

    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?

    0
  • 0
    Thats what I would do since the file doesnt need to be open all the time. You could always create the FileStream object, then use a StreamWriter to write to the FileStream after locking it. Then close the StreamWriter and exit the lock code block which will unlock the FileStream object. Theres a few different ways you can do it, experiment with them and see which way you like best.

    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.
    0
  • 0
    Thanks for the input works fine
    0