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.
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}");
});
}
}
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!");
}
}
2. Generating Reports
Top comments (0)