2015-07-11 47 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