All,
I am using lock() to try and sync threads writing to the same file, but my threads are still stepping on one another. Can anyone tell me why this doesn't work and how to fix it?
Here is some sample code. In the real program the writes are very infrequent, happening only when there is an error condition.
// This is Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Threadtest
{
class Program
{
static void Main(string[] args)
{
WriteToFile wtf1 = new WriteToFile("T1");
WriteToFile wtf2 = new WriteToFile("T2");
Thread t1 = new Thread(wtf1.writeJunk);
Thread t2 = new Thread(wtf2.writeJunk);
Console.WriteLine("Running...");
t1.Start();
t2.Start();
}
}
}
// This is WriteToFile.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
namespace Threadtest
{
class WriteToFile
{
private String threadName;
private System.Object lockThis = new System.Object();
public WriteToFile(String threadName)
{
this.threadName = threadName;
}
public void writeJunk()
{
while (true)
{
try
{
lock (lockThis)
{
using (StreamWriter outStream = File.AppendText("test.txt"))
{
outStream.WriteLine("This was written by thread: " + threadName);
}
}
}
catch (Exception e)
{
Console.WriteLine("We should never end up here, but sometimes we do.");
}
Thread.Sleep(100);
}
}
}
}
Thanks,
Bill