Riddle me thisFile access & Multi threading

time to read 1 min | 178 words

What would be the output of the following code?

var list = new List<Task>();

var fileStream = File.Open("test", FileMode.Create, FileAccess.ReadWrite, FileShare.None);
for (int i = 0; i < 150; i++)
{
    var index = i;
    var task = Task.Factory.StartNew(() =>
    {
        var buffer = Encoding.ASCII.GetBytes(index + "\r\n");
        fileStream.Write(buffer, 0, buffer.Length);
    });
    list.Add(task);
}


Task.WaitAll(list.ToArray());
fileStream.Flush(true);
fileStream.Dispose();

Please note that:

  • What order the data is saved is not important.
  • Preventing data corruption is important.

Can you guess?

More posts in "Riddle me this" series:

  1. (12 Oct 2010) File access & Multi threading
  2. (06 May 2010) String outputs
  3. (02 May 2010) Hard links & file moves