Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Riddle me this: File access & Multi threading

DZone's Guide to

Riddle me this: File access & Multi threading

·
Free Resource
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?


Topics:

Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}