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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
ArshadRank #2,492 · 564 reputationPosted Jan 14, 2008, 11:04 AM EST
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
Guest UserRank #1,422 · 1.2K reputationPosted Jan 14, 2008, 11:09 AM EST
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
Guest UserRank #1,422 · 1.2K reputationPosted Jan 14, 2008, 11:16 AM EST
http://msdn2.microsoft.com/en-us/library/c5kehkcz.aspx