Guide to the Language


The Async and Await Keywords


Download 2 Mb.
Pdf ko'rish
bet75/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   70   71   72   73   74   75   76   77   78
Bog'liq
C sharp

 The Async and Await Keywords
Introduced in C# 5.0, the async and await keywords allow asynchronous 
methods to be written with a simple structure that is similar to 
synchronous (regular) methods. The async modifier specifies that the 
method is asynchronous and that it can therefore contain one or more 
await expressions. An await expression consists of the await keyword 
followed by an awaitable method call.


178
class MyApp
{
async void MyAsync()
{
System.Console.Write("A");
await System.Threading.Tasks.Task.Delay(2000);
System.Console.Write("C");
}
}
This method will run synchronously until the await expression is 
reached, at which point the method is suspended and execution returns to 
the caller. The awaited task is scheduled to run in the background on the 
same thread. In this case the task is a timed delay that will complete after 
2000 milliseconds. Once the task is complete, the remainder of the async 
method will execute.
Calling the async method from Main will output “A” followed by “B” and 
then “C” after the delay. Note the use of the ReadKey method here to prevent 
the console program from exiting before the async method has finished.
static void Main()
{
new MyApp().MyAsync();
System.Console.Write("B");
System.Console.ReadKey();
}
 Async Return Types
In C# 5.0 an async method can have one of three built-in return types: 
Task, Task, and void. Specifying Task or void denotes that the method 
does not return a value, whereas Task means it will return a value of 
type T. In contrast to void, the Task and Task types are awaitable, so a 
Chapter 30 asynChronous Methods


179
caller can use the await keyword to suspend itself until after the task has 
finished. The void type is mainly used to define async event handlers, as 
event handlers require a void return type.

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   70   71   72   73   74   75   76   77   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling