Why Does My Asynchronous Code Run Synchronously When Debugging?

前端 未结 4 2018
野性不改
野性不改 2021-01-11 11:58

I am trying to implement a method called ReadAllLinesAsync using the async feature. I have produced the following code:

private static async Tas         


        
4条回答
  •  青春惊慌失措
    2021-01-11 12:16

    Visual Studio isn't actually executing the asynchronous callback synchronously. However, your code is structured in such a manner that it is "flooding" the UI thread with messages that you may not need to execute on a UI thread. Specifically, when FileReadAllLinesAsync resumes execution in the body of the while loop, it does so on the SynchronizationContext that was captured on the await line in the same method. What this means is for every line in your file, a message is posted back to the UI thread to execute 1 copy of the body of that while loop.

    You can resolve this issue by using ConfigureAwait(false) carefully.

    1. In FileReadAllLinesAsync, the body of the while loop is not sensitive to which thread it runs on, so you can use the following instead:

      while ((await reader.ReadLineAsync().ConfigureAwait(false)) != null)
      
    2. In Main, suppose you do want the MessageBox.Show line to execute on the UI thread (perhaps you also have a buttonLoad.Enabled = true statement there). You can (and will!) still get this behavior without any changes to Main, since you did not use ConfigureAwait(false) there.

    I suspect the delays you observe in the debugger are due to .NET's slower performance in managed/unmanaged code while a debugger is attached, so dispatching each of those millions of messages to the UI thread is up to 100x slower when you have the debugger attached. Rather than try to speed up that dispatching by disabling features, I suspect item #1 above will resolve the bulk of your problems immediately.

提交回复
热议问题