Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
18 Apr
2023

Asynchronous Programming in C#

by Shubham Batra

149

Welcome to Code2Night, where we delve into the exciting world of programming! In this article, we will embark on a journey to explore the fundamentals of Asynchronous Programming in C#. Are you ready to discover the power and versatility that this programming paradigm offers?


Asynchronous Programming

Async Programming

Asynchronous programming has become increasingly popular in modern software development, and C# has been updated to provide developers with better tools for writing asynchronous code. In this post, we'll take a closer look at the async and task keywords in C# and how they can be used to write more efficient and scalable applications.

The Basics of Asynchronous Programming in C#

Before we dive into async and tasks, let's briefly cover the basics of asynchronous programming in C#. When we say that a piece of code is asynchronous, we mean that it can run in the background while another code continues to execute. This is in contrast to synchronous code, which blocks the execution of other code until it completes.

One common use case for asynchronous programming is to improve the performance of I/O-bound operations, such as reading from or writing to a file, making a network request, or querying a database. In these scenarios, waiting for the I/O operation to complete can block the execution of other code, leading to poor performance.

To make an operation asynchronous in C#, we typically use the async keyword. This allows us to write code that looks similar to synchronous code but runs in the background. Let's take a look at an example:

public async Task<string> DownloadAsync(string url)
{
    using var client = new HttpClient();
    var response = await client.GetAsync(url);
    return await response.Content.ReadAsStringAsync();
}

In this code, we define a method called DownloadAsync that takes a URL and returns a Task. We mark the method with the async keyword to indicate that it's asynchronous. Inside the method, we create a new instance of the HttpClient class and use it to make a GET request to the specified URL. We use the await keyword to wait for the response to be returned and then read the content of the response using another await expression.

Note that we're not explicitly creating any threads or using any callbacks in this code. Instead, the async/await keywords allow us to write asynchronous code in a way that looks similar to synchronous code.

The Task Class

Now let's take a closer look at the Task class. A Task represents an operation that can be executed asynchronously. We can use the Task. Run a method to create a new task and execute it on a separate thread, like this:

public async Task<int> CalculateSumAsync()
{
    var task1 = Task.Run(() => CalculateSum(1, 2));
    var task2 = Task.Run(() => CalculateSum(3, 4));
    await Task.WhenAll(task1, task2);
    return task1.Result + task2.Result;
}

public int CalculateSum(int a, int b)
{
    // Simulate a long-running calculation
    Thread.Sleep(5000);
    return a + b;
}

In this code, we define two methods: CalculateSumAsync, which returns a Task, and CalculateSum, which takes two integers and returns their sum. Inside CalculateSumAsync, we create two tasks using the Task. Run the method and pass in lambda expressions that call the CalculateSum method. We then use the Task.WhenAll processes wait for both tasks to be complete before returning the sum of their results.

Note that we're using the Task. Run the method to execute the CalculateSum method on a separate thread. This is because CalculateSum contains a call to Thread. Sleep, which blocks the thread for 5 seconds. By running CalculateSum on a separate thread, we ensure that the main thread can continue executing other code while the calculation is running.

Using async and Task to Write Scalable Applications

By using async and Task, we can write code that can handle a large number of concurrent operations without blocking the execution of others.

  • |
  • Asynchronous Programming , Async in C# , Async in Aspnet , Multithreading

Comments

Follow Us On Social Media - Like Us On Facebook

Best Sellers

product 1

Hand Hug Bracelet For Women Men Cuff Bangle Adjustable Lover Couple Bracelets

Can be given as a gift to your family, relatives, or friends

Buy $15.99
product 1

Teddy bear hug bear plush toy bear cub

Can be given as a gift to your family, relatives, or friends


Buy $49.99

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Thank you for Downloading....!

Subscribe for more tutorials

Support our team

Continue with Downloading

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2023 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier