Reputation: 415735
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.
Upvotes: 4
Views: 9554
Reputation: 11
Use SyncLock
which makes sure only one thread opens the file at a time.
In the mean time the other processes do not crash but wait in a queue
.
Upvotes: 1
Reputation: 48265
There is nothing strange going on here. Imagine that you have a file "a.txt" and you open it in notepad 10 times. After that, you change the contents of the file and save it in every instance of notepad. Naturally, the last save you make is the one that is persisted to the file because it rewrites the previous 9 saves.
I think you've got the same behavior here. All the files are opened at the same time because you have a Thread.Sleep in each processing. So the i file to be saved overwrites the previous save (i-1).
EDIT: Try removing the Thread.Sleep(2000) and you'll have more logs in the file.
Upvotes: 5