我有一个测试方法,其中我正在测试异步文件写入:
[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);
}
}
异步文件写入代码:
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);
};
}
问题在于我的代码生成的文件没有包含所有预期值。
我期望在文件中看到从1到200的值,但实际上我看到了例如:
1
3
5
7
8
12
13
14
...
请在此处查看详细的文件:http://bit.ly/1JVMAyg
注意:请参见下面我的解决方案,可以修复未插入文件中的缺失项目的问题,但它破坏了@LasseV.Karlsen在他的评论中提到的多线程的整个想法。如果有更好的解决方案不会破坏多线程,请让我知道。