Synchronizing StreamWriter
I am trying to write to a file from several seperate threads. I keep getting IO exceptions saying I need to synchronize my streamwriters. How do I do this?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Guest UserPosted Jan 14, 2008, 4:16 PM
http://msdn2.microsoft.com/en-us/library/c5kehkcz.aspx
Guest UserPosted Jan 14, 2008, 4:09 PM
I would suggest creating a class that controls access to that file, implement it as a Singleton (so that there's only one instance of it within your app) and set up a write method in that class to receive the data that is to be written to the file. The code within the write method should be synchronzied so that only one thread at a time can access it.
Look at the MSDN article on TextWriter.Synchronized:
http://msdn2.microsoft.com/en-us/library/system.io.textwriter.synchronized(VS.71).aspx
ArshadPosted Jan 14, 2008, 4:04 PM
Hi.try this code without Using the Thread
using System;
using System.IO;
class Class
{
static void Main()
{
// Write out to text file
StreamWriter writer = File.CreateText("c:\\me.doc");
writer.WriteLine("Arshad you are Out of file.");
writer.Close();
// Read all lines from text file
StreamReader reader = File.OpenText("c:\\me.doc");
string line = reader.ReadLine();
while (line != null)
{
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();
}
}
Regards
Arshad Khan