Sometimes FileStream.ReadAsync terminates synchronously?

Give it a try. Set up a new Windows Forms application with one button and the following code for the button click event:

private async void button1_Click(object sender, EventArgs e)
{
    using (var file = File.OpenRead(@"C:\Temp\Sample.txt"))
    {
        byte[] buffer = new byte[4096];
        int threadId = Thread.CurrentThread.ManagedThreadId;
        int read = await file.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
        Debug.Assert(threadId != Thread.CurrentThread.ManagedThreadId);
    }
}

Then launch the application and quickly press the button. If your experience is not like mine, you will find that sometimes it works as expected, however, otherwise it Debug.Assertwill fail.

Based on my understanding, ConfigureAwait as described in Steven Cleary’s blog , the transfer falsefor continueOnCapturedContextshould indicate the task does not synchronize with the "main" context (the UI thread in this case), and this execution should continue in the thread pool.

? , ReadAsync , .. .

KB 156932 - - Windows:

/ (, ) , , - "", , ReadFile WriteFile TRUE. , -, . , , - "", .

? ReadAsync ? , ?

, COM-, , .

Windows 7 64-,.NET 4.5.1

+4
3

ReadAsync ?

. - , .NET.

, ?

, , Task.Run:

private async void button1_Click(object sender, EventArgs e)
{
  using (var file = File.OpenRead(@"C:\Temp\Sample.txt"))
  {
    byte[] buffer = new byte[4096];
    int threadId = Thread.CurrentThread.ManagedThreadId;
    int read = await file.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
    await Task.Run(() =>
    {
      Debug.Assert(threadId != Thread.CurrentThread.ManagedThreadId);
    }).ConfigureAwait(false);
  }
}

ConfigureAwait - , . ConfigureAwait , . await " " , , , ConfigureAwait .

+3

, , , . Task.Run(() => file.ReadAsync(buffer, 0, buffer.Length)) , , .

+2

When you use awaitin Task, if the task has already been completed, the code will execute synchronously. Then the call ConfigureAwaitin this task does not matter, since the other thread will not be involved.

It seems that if the data is in memory (because you are reading the same file repeatedly) it file.ReadAsynccan be executed synchronously, and therefore it will be terminated in the same thread.

0
source

Source: https://habr.com/ru/post/1532390/


All Articles