C# Asynchronous Method
C# asynchronous method is a special method that executes asynchronously. C# provides async modifier to make a method asynchronous. It is used to perform asynchronous tasks.
C# await expression is used to suspend the execution of a method.
If a method which uses async modifier does not contain await expression, executes synchronously.
Note: the async method cannot use ref or out parameters.
C# Asynchronous Method Return Types
An async method can use any one of the following return type.
- Task
- Task<TResult>
- Void (for event handlers)
- System.Threading.Tasks.ValueTask<TResult>
We should add asyncsuffix to the method name because of naming convention. Following is a typical syntax to define asynchronous method.
Syntax
We can use System.Net.HttpClient, Microsoft.Azure.EventHub.Core libraries that contain asynchronous operations.
In the following example, we are using using System.Net.Http; namespace to execute an asynchronous task.
This namespace is not available by default, so we need to install it by using the package manager console.
To open console, follow the instruction as we did in the following screenshot.
This will open a console window, where we can pass namespace name to install it in our project. Write the following command, as we did in the following screenshot.
After installing it, now we can execute the application.
C# Asynchronous Method Example
Output
length: 36006