我接下來的測試方法,其中我測試了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);
}
}
異步文件寫入代碼:
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的整體思路。我很高興看到一些人是否有更好的解決方案,不會打破多線程。
你有多個線程同時寫入同一個文件。這似乎不太可能結束。 –