The following code is just a simplified example to demonstrate my problem:
using System;
using System.IO;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication5
{
class Program
{
static string LogFile = @"C:\test.log";
static void Main(string[] args)
{
for (int i = 0;i<10;i++)
{
new Thread(new ParameterizedThreadStart(DoWork)).Start(i);
}
Console.ReadKey();
}
static void DoWork(object param)
{
int count = (int)param;
try
{
using (FileStream fs = new FileStream(LogFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(DateTime.Now + " - Start " + count.ToString());
Thread.Sleep(2000); // simulate doing some work
sw.WriteLine(DateTime.Now + " - End " + count.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(count.ToString() + ": " + e.Message);
return;
}
Console.WriteLine(count.ToString() + ": Done.");
}
}
}
The problem here is that typically only one entry makes it into the file, even though I call the method 10 times. The file should be open to allow sharing. As far as I can tell no exceptions are thrown. What's going on?
In the real code that this example shadows, each call to DoWork is actually in a separate process, though testing shows that the results are the same-- if I can fix it here I can fix it there.