Introduction
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 article, we will focus on Task.Run and will learn how we can perform background work with Task.Run.
What is a 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 is completed, and the Task object is marked as completed, faulted, or canceled, depending on the outcome.
Main Thread Thread Pool
| |
| |
| Task.Run |
|---------> Task Created |
| |
| |
| |
| | Task Queued
| |-----------------> Task Executed
| | |
| | |
| Task Continuation | | Task Completed
|<----------------------------|<---------------------|
| |
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.
Logging
This is a perfect use case, and each and every application is doing logging. Let’s understand how we can improve performance.
Suppose after a successful database operation, we want to log operation results, and if we do so sequentially, then UI will remain blocked. Of course, this is not important work from the UI user or client, so if we perform Logging in the background, then that will increase response time.
Detailed implementation
Logger Service: we are logging in using Task.Run in the 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}");
});
}
}
Harshit PandeyPosted Nov 20, 2024, 10:09 AM
Nice article!!!