European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core 9.0 Hosting - HostForLIFE :: Task: Synchronous vs. Asynchronous.Task and WaitAll.WhenEverything in.NET

clock July 9, 2024 07:09 by author Peter

Asynchronous programming in C# frequently entails doing several tasks at once. Task and Split are two popular approaches to managing many tasks.Task.WhenAll and WaitAll. Despite their apparent similarities, they have different functions and are employed in various contexts. The distinctions between Task.WaitAll and Task.WhenAll are examined in this article, along with real-world examples to show how to use both.


What is Task.WaitAll?
Assignment.The synchronous function WaitAll stops the calling thread after each of the supplied tasks is finished. It's helpful when you have to make sure that a group of tasks is completed before moving on, but it does so in a blocking way, meaning that Task is called by the thread.Until every task is completed, WaitAll is in use.

Example Usage of Task.WaitAll
using System;
using System.Threading.Tasks;
class Program
{
    static void Main()
    {
        Task task1 = Task.Run(() => PerformTask(1));
        Task task2 = Task.Run(() => PerformTask(2));
        Task task3 = Task.Run(() => PerformTask(3));
        Task.WaitAll(task1, task2, task3); // Blocks until all tasks complete
        Console.WriteLine("All tasks completed.");
    }
    static void PerformTask(int taskId)
    {
        Console.WriteLine($"Task {taskId} starting.");
        Task.Delay(1000).Wait(); // Simulate work
        Console.WriteLine($"Task {taskId} completed.");
    }
}


In this example, Task.WaitAll blocks the main thread until all three tasks are complete.

What is Task.WhenAll?

Task.WhenAll is an asynchronous method that returns a single task that is completed when all the provided tasks have been completed. Unlike Task.WaitAll, it does not block the calling thread. Instead, it allows the calling code to continue executing asynchronously.

Example Usage of Task.WhenAll

using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main()
    {
        Task task1 = Task.Run(() => PerformTask(1));
        Task task2 = Task.Run(() => PerformTask(2));
        Task task3 = Task.Run(() => PerformTask(3));
        await Task.WhenAll(task1, task2, task3); // Waits for all tasks to complete asynchronously
        Console.WriteLine("All tasks completed.");
    }
    static void PerformTask(int taskId)
    {
        Console.WriteLine($"Task {taskId} starting.");
        Task.Delay(1000).Wait(); // Simulate work
        Console.WriteLine($"Task {taskId} completed.");
    }
}


In this example, Task.WhenAll allows the main method to await the completion of all tasks without blocking the calling thread.

Key Differences
Blocking vs. Non-blocking

  • Task.WaitAll: Blocks the calling thread until all tasks are complete.
  • Task.WhenAll: Returns a task that can be awaited, allowing the calling thread to continue execution asynchronously.

Return Type

  • Task.WaitAll: Does not return a value.
  • Task.WhenAll: Returns a Task that represents the completion of all provided tasks.

Usage Scenario

  • Task.WaitAll: Used when you need to block until tasks are complete, typically in non-UI or console applications.
  • Task.WhenAll: Used in asynchronous programming, especially in UI applications where blocking the main thread is undesirable.

Practical Use Cases
When to Use Task.WaitAll

  • In console applications where you need to ensure that certain tasks are completed before moving on.
  • When you are dealing with legacy code that doesn’t support async/await patterns.

When to Use Task.WhenAll

  • In UI applications keep the interface responsive.
  • In web applications handle multiple asynchronous operations without blocking the main thread.

Conclusion
Task.WaitAll and Task.WhenAll are essential tools in C# for handling multiple tasks. Use Task.WaitAll when you need to block the calling thread until tasks are complete, and Task.WhenAll for asynchronous waiting. Understanding their differences and appropriate use cases can help you write more efficient and responsive applications.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Resilience in a.NET 8 Web API Implementation

clock July 2, 2024 08:16 by author Peter

Creating robust APIs is more important than ever in the age of modern web development, especially with all these third-party integration we rely on. In this Blog, We will be guiding you how to introduce resilience in. Create an HTTP Client in a. Extensions. Http. Resilience library. In this section, we will take a look at features like setting up retry policies with exponential backoff and timeouts to make your API more resilient against the transient faults.

Step 1. Create a new. NET 8 Web API project Step First, if you have no existing Project then create new with. NET CLI dotnet new web or starting with the default Web API template.

Step 2. Install the Microsoft.AspNetCore. Extensions. Http. Resilience library via NuGet:
dotnet add package Microsoft.Extensions.Http.Resilience --version 8.0.0

Step 3. Configure Resilience in Program.cs
Modify the Program.cs file to set up HttpClient with resilience policies provided by Microsoft.Extensions.Http.Resilience. Here, we will define retry policies and timeouts.
//Add resilience pipeline
builder.Services.AddResiliencePipeline("default", x =>
{
    x.AddRetry(new Polly.Retry.RetryStrategyOptions
    {
        ShouldHandle = new PredicateBuilder().Handle<Exception>(),
        Delay = TimeSpan.FromSeconds(2),
        MaxRetryAttempts = 2,
        BackoffType = DelayBackoffType.Exponential,
        UseJitter = true
    })
    .AddTimeout(TimeSpan.FromSeconds(30));
});

Step 4. Use the Resilient HttpClient in a Service
Next, we'll inject and use the configured HttpClient in your Service. This example shows how to fetch data from an external API using the resilient HttpClient.
public class WeatherService
{
    private readonly HttpClient _httpClient;
    private readonly ResiliencePipelineProvider<string> _resiliencePipelineProvider;
    public WeatherService(HttpClient httpClient,
                         ResiliencePipelineProvider<string> resiliencePipelineProvider)
    {
        _httpClient = httpClient;
        _resiliencePipelineProvider = resiliencePipelineProvider;

    }
    public async Task<string> GetWeatherAsync()
    {
        var pipeline = _resiliencePipelineProvider.GetPipeline("default");
        var response = await pipeline
            .ExecuteAsync( async ct=> await _httpClient.GetAsync($"https://localhost:7187/weatherforecast",ct));

        return await response.Content.ReadAsStringAsync();
    }

}


Step 5. Add the endpoint in the Program.cs
app.MapGet("/weatherService/weather", async (WeatherService weatherService) =>
{
    var result = await weatherService.GetWeatherAsync();
    return result;
})
    .WithName("GetWeather")
    .WithOpenApi();


Step 6. Run the Application
Finally, run your application and navigate to the endpoint to see the resilient HttpClient in action.
References

Please refer to the below links for more details.

  • Building resilient cloud services with .NET 8
  • Learning from Microsoft

Conclusion
By following these steps, you have integrated resilience into your .NET 8 Web API project using Microsoft.Extensions.Http.Resilience library. The retry policies, circuit breaker settings, and timeouts will help ensure your API is robust against transient faults, improving its reliability and user experience.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in