views:

296

answers:

1

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.

+4  A: 

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.

bruno conde
Of course it's not strange :) I was just trying to consider which non-strange thing was going on. This makes sense, thanks.
Joel Coehoorn
"it rewrites the previous 9 saves", but, isn't that what FileMode.Append should avoid?
ptor
@ptor, yes but the Append position is the same when you open all the files almost at the same time. So, when a Write closes, the Append position of the next file doesn't change and the data gets overrided. Try outputting different sized data on different iterations and you'll see strange results in the text file.
bruno conde