DEV Community

Cover image for Improve Application Performance using “Fire and Forget” in .NET Core
.Net Labs
.Net Labs

Posted on

2

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up