Async await c# là gì

Async and Await are the two từ khoá that help us to lớn program asynchronously. An async keywords is a method that performs asynchronous tasks such as fetching data from a database, reading a file, etc, they can be marked as “async”. Whereas await từ khoá making “await” to lớn a statement means suspending the execution of the async method it is residing in until the asynchronous task completes. After suspension, the control goes back to the caller method. Once the task completes, the control comes back to lớn the states where await is mentioned và executes the remaining statements in the enclosing method.

Bạn đang xem: Async await c# là gì

Let us see the behavior of the code with và without async and await operators.

Synchronous Programming:

In general, the code executes sequentially i.e statements are executed one after the other. Let us take a small example of a school that has classes 11 and 12.

The first thing school does is start the assembly which might be having morning prayer, pledge, daily updates, etcAfter the assembly, teachings begin for class 11 và class 12.

In our synchronous code below, we will be using the Stopwatch lớn record the execution time taken by the code. We have three methods in which Thread.Sleep(n) is specified to simulate that these methods take some time lớn run.

Xem thêm: Nên Xịt Nước Hoa Ở Đâu - Xịt Nước Hoa Ở Đâu Để Quyến Rũ Suốt Cả Ngày

Asynchronous Programming:

Using asynchronous programming indicates that a method can execute without waiting for another method lớn complete. Using async and await, we can run the methods above parallelly.

Example 2:

Notice that these methods above have run parallelly and the execution time taken will be the same as the time taken by StartSchoolAssembly() as this is the method that is taking the longest time.

Do we really want this output? How can we start teaching classes 11 & 12 without starting the school assembly? Let us wait for the school assembly lớn finish irrespective of how long it is taking & later the teaching for classes 11 & 12 can begin.

Here task1 represents the school assembly. Therefore let us use the await keyword to wait for the school assembly task to finish.

Example 3:

Notice that the TeachClass12() and TeachClass11() execute only after the StartSchoolAssembly() completes. The school assembly takes 8 seconds to complete. Class 11 finishes the class soon as it takes only 2 seconds. Class 12 finishes a bit late as it takes 3 seconds. Therefore the total execution time is 8s + 3s = 11s.
We use cookies to lớn ensure you have the best browsing experience on our website. By using our site, youacknowledge that you have read & understood ourCookie Policy & Privacy PolicyGot It !