Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Call a method Asynchronously in C#
Asynchronous programming in C# is an efficient approach for handling operations that may be blocked or delayed. In synchronous processing, if an operation is blocked, the entire application waits, causing it to become unresponsive and take longer to complete tasks.
Using the asynchronous approach, applications can continue executing other tasks while waiting for blocked operations to complete. This is especially important in GUI applications where blocking the main thread causes the interface to freeze.
The Problem with Synchronous Code
In GUI applications, when synchronous operations take too long, the application shows "not responding" messages because the main thread is blocked −
private void OnRequestDownload(object sender, RoutedEventArgs e) {
var req = HttpWebRequest.Create(_requestedUri);
var res = req.GetResponse(); // Blocks the UI thread
}
The Solution: async and await Keywords
The async and await keywords solve this problem by allowing the method to yield control back to the caller while waiting for the operation to complete −
private async void OnRequestDownload(object sender, RoutedEventArgs e) {
var req = HttpWebRequest.Create(_requestedUri);
var res = await req.GetResponseAsync(); // Non-blocking
}
Syntax
Following is the syntax for declaring an async method −
public async Task MethodName() {
var result = await SomeAsyncOperation();
return result;
}
For methods that don't return a value −
public async Task MethodName() {
await SomeAsyncOperation();
}
Using async/await with HTTP Requests
Example
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program {
private static readonly HttpClient client = new HttpClient();
public static async Task Main(string[] args) {
Console.WriteLine("Starting download...");
string content = await DownloadContentAsync("https://httpbin.org/delay/2");
Console.WriteLine("Download completed!");
Console.WriteLine("Content length: " + content.Length + " characters");
}
private static async Task<string> DownloadContentAsync(string url) {
Console.WriteLine("Requesting: " + url);
HttpResponseMessage response = await client.GetAsync(url);
string content = await response.Content.ReadAsStringAsync();
return content;
}
}
The output of the above code is −
Starting download... Requesting: https://httpbin.org/delay/2 Download completed! Content length: 315 characters
Using Task.Run for CPU-Intensive Operations
Example
using System;
using System.Threading.Tasks;
class Program {
public static async Task Main(string[] args) {
Console.WriteLine("Starting calculations...");
int result = await CalculateAsync(1000000);
Console.WriteLine("Calculation completed!");
Console.WriteLine("Result: " + result);
}
private static async Task<int> CalculateAsync(int limit) {
return await Task.Run(() => {
Console.WriteLine("Performing heavy calculation...");
int sum = 0;
for (int i = 1; i <= limit; i++) {
sum += i;
}
return sum;
});
}
}
The output of the above code is −
Starting calculations... Performing heavy calculation... Calculation completed! Result: 1784293664
Key Rules for async/await
| Rule | Description |
|---|---|
| async methods return Task or Task<T> | Except for event handlers which can be async void |
| await can only be used in async methods | The method must be marked with async keyword |
| async methods run synchronously until await | Control returns to caller at the first await |
| Don't block on async code | Use await instead of .Result or .Wait() |
Conclusion
Asynchronous programming with async and await prevents UI freezing and improves application responsiveness. Use async methods for I/O operations like web requests, file operations, and database calls to keep your application responsive while waiting for these operations to complete.
