Logo

dev-resources.site

for different kinds of informations.

Improve Application Performance using “Fire and Forget” in .NET Core

Published at
12/30/2024
Categories
webdev
api
dotnetcore
csharp
Author
devesh_omar_b599bc4be3ee7
Categories
4 categories in total
webdev
open
api
open
dotnetcore
open
csharp
open
Author
25 person written this
devesh_omar_b599bc4be3ee7
open
Improve Application Performance using “Fire and Forget” in .NET Core

Fire and Forget is nothing but it is Executing Task in Background

Deep dive into Task.Run()

By using the fire-and-forget approach appropriately, you can improve the responsiveness and performance of your .NET Core applications while ensuring that important background tasks are performed efficiently.

In this tutorial we will focus on Task.Run and will learn how we can perform background work with Task.Run

What is Task.Run ?

Task.Run queues the specified work to run on the thread pool and returns a Task object representing that work. This allows the work to be performed asynchronously without blocking the main thread.

How Task.Run Works: Control Flow Diagram

Task Creation: The Task.Run method creates a new Task object.
Queueing Work: The task is queued to the thread pool.
Thread Pool Execution: A thread pool thread picks up the task and executes it.

Task Completion: The task completes and the Task object is marked as completed, faulted, or canceled, depending on the outcome.

Image description

Task.Run in .NET Core allows you to offload work to a background thread, which can help improve the responsiveness of your application by freeing up the main thread for other tasks

Below is few Real time use cases where we can use Task.Run

Real Time Examples

Logging
This is perfect use case and each and every application doing logging Let’s understand how we can improve performance

Suppose after successful database operation we want to log operation results and if we do sequentially then UI will remain block and OfCourse this is not important work from UI user or client, so if we perform Logging in background then that will increase response time.

Detailed implementation

Logger Service: we are logging using Task.Run in code below

public interface ILoggingService
{
    void LogInformation(string message);
}

public class LoggingService : ILoggingService
{
    public void LogInformation(string message)
    {
        Task.Run(() => 
        {
            // Simulate logging operation
            System.IO.File.AppendAllText("log.txt", $"{DateTime.UtcNow}: {message}{Environment.NewLine}");
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Controller

[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
    private readonly ILoggingService _loggingService;

    public ExampleController(ILoggingService loggingService)
    {
        _loggingService = loggingService;
    }

    [HttpGet]
    public IActionResult Get()
    {  
         // Reading Work to DB

        ///

        _loggingService.LogInformation("Get method called.");
        return Ok("Hello, world!");
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Generating Reports

Please click here to see complete tutorial

dotnetcore Article's
30 articles in total
Favicon
.Net tarixi
Favicon
Oh bless me, Father, I have done something unholy: Installing .NET Core on Apple Silicon
Favicon
How to use Scoped service from Singleton Service in .Net Core
Favicon
How to add a Custom fields to Header in .NET Core Web API ?
Favicon
c#(.Net) - Basic Authentication WEB API
Favicon
CRUD operations on Arrays
Favicon
Working with interfaces
Favicon
Iterations
Favicon
Protfolio Website
Favicon
Dependency injection validation error in ASP.NET Core projects
Favicon
.Net Core and Kafka
Favicon
C# Null-Conditional (?.) & Null-Coalescing (??) Operators Explained
Favicon
Change a .Net Console application into an web application
Favicon
Efficient Bulk Operations with UkrGuru.Sql
Favicon
Improve Application Performance using “Fire and Forget” in .NET Core
Favicon
API Versioning in .Net Core.
Favicon
Move objects from one folder to other in the same S3 Bucket using C# in AWS
Favicon
🎉 We Made It: Trending in .NET on Dev.to! 🚀
Favicon
.NET 9 Improvements for ASP.NET Core: Open API, Performance, and Tooling
Favicon
.Net Core Microservice Communication Using Kafka.
Favicon
Getting Started with .NET and Docker Tutorial
Favicon
Experimental attribute in C# is a powerful tool : Let's explore
Favicon
Implementing Chain of Responsibility Pattern in C# : Middleware's Design Pattern
Favicon
How to create a background email sender with outbox pattern integration
Favicon
The End of Microsoft's Monopoly on ASP.NET
Favicon
.NET Core MVC Project Structure : Implementing a Generic Service and Repository Pattern
Favicon
Did you know? How .NET Achieving Language Interoperability (C# + VB.NET = Same Application)
Favicon
These 10+ comparisons cover entire SQL concepts, Is it?
Favicon
NET 9 BinaryFormatter migration paths
Favicon
How to create a background email sender

Featured ones: