I have the next test method where I am testing the async file write:
[TestMethod]
public async Task TestMethod1()
{
List<Task> tasks = null;
int x = 1;
int step = 10;
for (int i = step; i <=200; i = i + step)
{
tasks = Enumerable.Range(x, step).Select(async y =>
{
await TextFile.WriteTextAsync("file.txt", String.Format("{0}n", y));
}).ToList();
x = i + 1;
await Task.WhenAll(tasks);
}
}
Async file write code:
public static async Task WriteTextAsync(string filePath, string text)
{
byte[] encodedText = Encoding.Unicode.GetBytes(text);
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.ReadWrite,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
}
The problem is that my code producing the file that not contained all expected values.
I am expecting to see the values from 1 to 200 in the file but instead I have e.g
1
3
5
7
8
12
13
14
...
See detailed file here http://bit.ly/1JVMAyg
May be some one have an idea what is going on and how to fix that?
Source: .net