使用/不使用await调用FileStream.ReadAsync的差异

时间:2014-02-05 21:26:27

标签: c# task-parallel-library async-await

我决定编写一个计算文件中字节数的函数。

“正常”和异步。

所以我编写了以下函数:

功能1

public static async Task<int[]> ByteFrequencyCountAsync(string fname)
{
    // freqs
    int[] counted = new int[256];
    // buf len
    int blen = FileAnalisys.ChooseBuffLenght(fname);
    // buf
    byte[] buf = new byte[blen];

    int bytesread;

       using (FileStream fs = new FileStream
                                            (
                                              fname,
                                              FileMode.Open,
                                              FileAccess.Read,
                                              FileShare.Read,
                                              blen,
                                              FileOptions.Asynchronous
                                            ))
       {

          while ( ( bytesread = await fs.ReadAsync(buf, 0, blen) ) != 0)
          {

              foreach (byte b in buf)
                 counted[b]++;

          }
        }

        return counted;
}

功能2

public static int[] ByteFrequencyCount(string fname)
{

    Task<int[]> bytecount = Task.Run<int[]>( () =>
    {              
        // freqs
        int[] counted = new int[256];
        // buf len
        int blen = FileAnalisys.ChooseBuffLenght(fname);
        // buf
        byte[] buf = new byte[blen];

        int bytesread;

        using (FileStream fs = new FileStream
                                            (
                                              fname,
                                              FileMode.Open,
                                              FileAccess.Read,
                                              FileShare.Read,
                                              blen,
                                              FileOptions.Asynchronous
                                            ))                                                            
        {

             while ( ( bytesread = fs.ReadAsync(buf, 0, blen).Result ) != 0)
             {
                 foreach (byte b in buf)
                     counted[b]++;

              }            
         }

         return counted;
     });
        return bytecount.Result;
 }

我认为功能1异步执行读取而功能2同步执行。

功能1

while ( ( bytesread = await fs.ReadAsync(buf, 0, blen) ) != 0)

功能2

while ( ( bytesread = fs.ReadAsync(buf, 0, blen).Result ) != 0)

简而言之。我想没有等待并且没有标记为异步的任务是通过线程池执行但是同步。所以我可以为fs.Read更改fs.ReadASync,但没有任何反应。

需要一只手,因为我有点困惑。

EDIT1: 功能2应该是同步的,所以我的问题是:

代码有效,但我认为使用FileStream.Asynchronous是没有意义的。

我认为使用fs.ReadASync代替fs.Read并没有什么好处。所以它应该被替换为 fs.Read。

1 个答案:

答案 0 :(得分:0)

使用Async标记方法并不是这样。只有当awaiter是用户时,方法体才会以异步方式执行。您可以看到Async / Await如何在这里工作的一个很好的探索Async/Await under the sheets

Task.Run将在阻止&amp;同步方式。

FileStream.ReadAsync()方法返回一个等待的任务&lt;&gt;所以它没用。如果你不想但是有任务,你也可以不必等待它,你也可以在需要的时候取消它。

查看here是否正确使用

相关问题