2015-07-11 73 views
4

我接下來的測試方法,其中我測試了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的整體思路。我很高興看到一些人是否有更好的解決方案,不會打破多線程。

+4

你有多個線程同時寫入同一個文件。這似乎不太可能結束。 –

回答

0

感謝@JonSkeet。我懂了。我不得不限制訪問「WriteTextAsync」的方法,這裏是我的解決方案:

private static SemaphoreSlim _thread= new SemaphoreSlim(1);  
public static async Task WriteTextAsync(string filePath, string text) 
{ 
    byte[] encodedText = Encoding.Unicode.GetBytes(text); 
    await _sync.WaitAsync(); 
    try 
    { 

     using (FileStream sourceStream = new FileStream(filePath, 
      FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 
      bufferSize: 4096, useAsync: true)) 
     { 
      await sourceStream.WriteAsync(encodedText, 0, encodedText.Length); 
     }; 
    } 

    catch(Exception ex) 
    { 
     Debug.WriteLine(ex.ToString()); 
    } 
    finally 
    { 
     _thread.Release(); 
    } 
} 

注意: 該解決方案是修復與遺漏項目問題didnt插入到該文件,但現在它被限制WriteTextAsync與僅僅只有一個線程訪問提到的時間點的文件@ LasseV.Karlsen。

所以看起來像我的解決方案解決了這個問題,但突破多線程的整體思路,我很高興地看到,如果有一個人有更好的解決方案,不會打破多線程。

+3

但是,如果你在一個時間內結束了只有一個線程寫入文件,爲什麼整個線程的事情呢?你基本上是將N個購物者送到商店,但商店只有一條結賬線,或者我錯過了什麼? –

+0

@LasseVKarlsen其實我看不出有什麼的線程在所有...除非默認的調度是,嗯..默認調度... – Aron

+0

@Aron我猜ü權 – Kuncevic