C# Implementing Multi-Threading and Asynchronous Processing

C# Implementing Multi-Threading and Asynchronous Processing

Table of contents

Asynchronous programming is a programming paradigm that allows a program to continue executing while waiting for a time-consuming operation to complete. In .NET web development, asynchronous programming is used to improve the scalability and responsiveness of web applications.

In traditional synchronous programming, a web server would process one request at a time, blocking execution until the request was completed. This means that if many requests are being processed simultaneously, the server could become overloaded and unresponsive.

With asynchronous programming, the server can handle multiple requests simultaneously, allowing it to process more requests at once and respond to clients more quickly. This is achieved by using asynchronous methods that allow the program to continue executing while waiting for a time-consuming operation, such as a database query or file I/O, to complete.

In .NET web development, asynchronous programming can be used in several ways, including:

  1. Handling HTTP requests: ASP.NET Core allows developers to handle HTTP requests asynchronously, which can improve the scalability and performance of web applications.

  2. Database access: Asynchronous programming can be used to improve the performance of database queries, allowing multiple queries to be executed simultaneously.

  3. File I/O: Asynchronous programming can also be used to improve the performance of file I/O operations, allowing multiple operations to be executed simultaneously.

  4. External API calls: Asynchronous programming can be used to make external API calls more efficient, allowing the program to continue executing while waiting for the API response.

Continuing with the program flow, there are several ways to write asynchronous code. Using the Task class allows you to take advantage of the Thread Pool, so you don't need to manage your Thread, instead, the system is taking care of them. The goal of the Task Parallel Library is to provide a high level of abstraction, it simplifies the action to a task that handles the sequence of processing for you.

Tasks are constructs, they offer you a promise that work will be completed.

Task single operation with no return.

Task<T> single operation which returns a value of type T.

docs.microsoft.com/en-us/dotnet/standard/as..

async - await

Provides you with a clean way to interact with the background thread and keep the caller of the async method responsive

public async Task<ActionResult> Login(LoginViewModel model)
{
    // Make an API call to authenticate the user
    HttpResponseMessage response = await httpClient.PostAsync("api/user/login", new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"));

    // Check if the API call was successful
    if (response.IsSuccessStatusCode)
    {
        // Get the user data from the API response
        var userData = JsonConvert.DeserializeObject<UserDataViewModel>(await response.Content.ReadAsStringAsync());

        // Save the user data to the session
        HttpContext.Session.SetString("UserId", userData.Id);
        HttpContext.Session.SetString("Username", userData.Username);

        // Redirect to the home page
        return RedirectToAction("Index", "Home");
    }
    else
    {
        // Display an error message
        ModelState.AddModelError("", "Invalid username or password");
        return View(model);
    }
}

In this example, we are using the HttpClient class to make an API call to the /api/user/login endpoint, passing in the user's login credentials as a serialized JSON object. The await keyword is used to asynchronously wait for the API call to complete before continuing execution.

If the API call is successful, we deserialize the user data from the API response and save it to the user's session. If the API call fails, we display an error message to the user.

Note that to use async/await in an ASP.NET Core web application, you need to mark the controller action method with the async keyword and return a Task<ActionResult>.

Overall, asynchronous programming is a powerful tool in .NET web development, allowing developers to improve the scalability and responsiveness of web applications by handling multiple requests simultaneously and improving the performance of time-consuming operations.

Did you find this article valuable?

Support Nestor Rojas by becoming a sponsor. Any amount is appreciated!