How does C# 5.0's async-await feature differ from the TPL?

后端 未结 7 1665
孤城傲影
孤城傲影 2020-12-07 10:48

I don\'t see the different between C#\'s (and VB\'s) new async features, and .NET 4.0\'s Task Parallel Library. Take, for example, Eric Lippert\'s code from here:

         


        
7条回答
  •  死守一世寂寞
    2020-12-07 11:07

    The call to FetchAsync() will still block until it completes (unless a statement within calls await?) The key is that control is returned to the caller (because the ArchiveDocuments method itself is declared as async). So the caller can happily continue processing UI logic, respond to events, etc.

    When FetchAsync() completes, it interrupts the caller to finish the loop. It hits ArchiveAsync() and blocks, but ArchiveAsync() probably just creates a new task, starts it, and returns the task. This allows the second loop to begin, while the task is processing.

    The second loop hits FetchAsync() and blocks, returning control to the caller. When FetchAsync() completes, it again interrupts the caller to continue processing. It then hits await archive, which returns control to the caller until the Task created in loop 1 completes. Once that task is complete, the caller is again interrupted, and the second loop calls ArchiveAsync(), which gets a started task and begins loop 3, repeat ad nauseum.

    The key is returning control to the caller while the heavy lifters are executing.

提交回复
热议问题