Updated April 11, 2023
Introduction to C# Asynchronous
A special method in C# which executes asynchronously is called Asynchronous method and a method can be made asynchronous by using the modifier async and asynchronous tasks can be performed using asynchronous methods in C# and a method execution can be suspended by using await expression in C# and if this await expression is not present in a method which has the modifier async, that corresponding method is executed synchronously and asynchronously even though the method is an asynchronous method and the return types of an asynchronous methods are Task, Task<TResult>, Void(for event handlers) and System.Threading.Tasks.ValueTask<TResult>.
Syntax of C# Asynchronous method:
public async Task<int> Method_name()
{
// Block of code
}
- async is the modifier used.
- Methodname is the name given to the method.
Working of Asynchronous Method in C#
- Whenever the logic in the program requires using of await able tasks, we make use of asynchronous method using which we can perform operations that take a long time to complete like downloading something from the web, reading a huge file, or performing calculations that are really complex without disturbing or blocking the normal execution of the application. This is possible by using the modifiers async and await in our program.
- The asynchronous method is called separately with the task associated with it which performs the task that is not related to the flow of the program and it is made to await within which it could have finished the task and returns the respective value as per its definition which can be used in the following statements or it could be still performing the task while the control goes to the caller of the asynchronous method and resumes execution of the program without interrupting the execution of the task and once the task is complete, the rest of the asynchronous method is executed and it returns the respective value as per its definition.
Examples of C# Asynchronous
Given below are the examples mentioned :
Example #1
C# program to demonstrate Asynchronous method in a program to read the contents of the file and determine the count of the number of characters in the file.
Code:
using System;
using System.IO;
using System.Threading.Tasks;
//a class called check is defined
class Check
{
//main method is called
public static void Main()
{
//a file is created
String pat = @"D:\Ext.txt";
//an instance of the string writer class is created, and the path of the file is passed as a parameter to append text to the file
using (StreamWritersw = File.AppendText(pat))
{
//data to be appended to the file is included
sw.WriteLine("Welcome to StreamWriter class in C#");
//the instance of the streamwriter class is closed after writing data to the File
sw.Close();
}
//ReadFileusingAsync method is called by creating a task and the control moves to ReadFileusingAsync method
Task<int>taskname = ReadFileusingAsync();
//When the control reaches await modifier in ReadFileusingAsync method, the control returns here as the task is still going on and the following statements are executed
Console.WriteLine("Task is being performed by the asynchronous method and we are asked to wait until the completion of the task using await method");
string givemeinput = Console.ReadLine();
Console.WriteLine("The flow of the program is resumed once the task is completed by the asynchronous method and the value is returned " + givemeinput);
//We are waiting to receive the value from the task of asynchronous method in case the value is not returned yet.
taskname.Wait();
//We have used Result method to obtain the value returned from the asynchronous method after the completion of task assigned to it
var z = taskname.Result;
Console.WriteLine("The number of characters in the file are: " + z);
Console.WriteLine("The program has completed its normal execution and the asynchronous method has read the file to count the number of characters in the file");
Console.ReadLine();
}
static async Task<int>ReadFileusingAsync()
{
string fileread = @"D:\Ext.txt";
//The following statements are executed which can take a longer time
Console.WriteLine("We have opened the file to read the contents of the file");
int counter = 0;
using (StreamReader read = new StreamReader(fileread))
{
//await modifier is used to ask the caller function to wait till the reading of the file is complete
string vart = await read.ReadToEndAsync();
counter += vart.Length;
//This is the unnecessary code that is time consuming we have included for the sake of explanation
for (int r = 0; r < 20000; r++)
{
int z = vart.GetHashCode();
if (z == 0)
{
counter--;
}
}
}
Console.WriteLine("We are done reading the file");
return counter;
}
}
Output:
Explanation:
- In the above program, a class called check is defined and then the main method is called within which we are creating a file and writing contents into the file.
- Then a task is created which calls the asynchronous method ReadFileusingAsync and the control moves to that method in which the task of reading the contents of the file is performed.
- Then the length of the characters is obtained by using length function while reading the contents of the file and the same is returned to the calling method.
- The calling method waits till the control goes back to it and then the normal flow of the program is resumed to display the result.
Example #2
C# program to demonstrate Asynchronous method in a program.
Code:
using System;
using System.Threading.Tasks;
//a class called check is defined
class Check
{
static void Main()
{
while (true)
{
//the asynchronous method is called.
keeptrying();
string res = Console.ReadLine();
Console.WriteLine("The input given by the user while the computation is going on by the asynchronous method is: " + res);
}
}
static async void keeptrying()
{
//the caller function is asked to await
int t = await Task.Run(() =>compute());
Console.WriteLine("The total digits count in the string is: " + t);
}
static intcompute()
{
int counter = 0;
for (int a = 0; a < 10; a++)
{
for (int b = 0; b < 1000; b++)
{
string value = b.ToString();
counter += value.Length;
}
}
return counter;
}
}
Output:
Explanation:
- In the above program, a class called check is defined.
- Then the main method is called within which the asynchronous method is called and the control moves to the asynchronous method where the total count of the digits in a string is computed which asks the caller method to await while the main method continues displaying the input provided by the user.
Recommended Articles
This is a guide to C# Asynchronous. Here we discuss the introduction to C# Asynchronous, working of asynchronous method along with programming examples. You may also have a look at the following articles to learn more –