Why Use Async/Await Over Normal Threading or Tasks?

后端 未结 5 1455
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 04:15

I\'ve been reading a lot about async and await, and at first I didn\'t get it because I didn\'t properly understand threading or tasks. But after getting to grips with both

5条回答
  •  忘掉有多难
    2020-12-01 05:14

    Comparing async and await with threads is like comparing apples and pipe wrenches. From 10,000 feet they may look similar, but they are very different solutions to very different problems.

    async and await are all about asynchronous programming; specifically, allowing a method to pause itself while it's waiting for some operation. When the method pauses, it returns to its caller (usually returning a task, which is completed when the method completes).

    I assume you're familiar with threading, which is about managing threads. The closest parallel to a thread in the async world is Task.Run, which starts executing some code on a background thread and returns a task which is completed when that code completes.

    async and await were carefully designed to be thread-agnostic. So they work quite well in the UI thread of WPF/Win8/WinForms/Silverlight/WP apps, keeping the UI thread responsive without tying up thread pool resources. They also work quite well in multithreaded scenarios such as ASP.NET.

    If you're looking for a good intro to async/await, I wrote up one on my blog which has links to additional recommended reading.

提交回复
热议问题