Thursday, October 24, 2024

C# Difference between Task.Run and Task.WaitAll


In C#, Task.Run and Task.WaitAll are methods used to work with asynchronous tasks in a multi-threaded environment. They are part of the Task Parallel Library (TPL) and are used to manage and execute asynchronous operations.

1. Task.Run:
Task.Run is a method that creates and starts a new task on a ThreadPool thread. It allows you to execute a specified delegate (usually a lambda expression or a method) asynchronously. This method returns a Task object that represents the asynchronous operation. 
Example usage of Task.Run:
 Task.Run(() => SomeMethodAsync()); // Start a new task to run SomeMethodAsync asynchronously
In this example, SomeMethodAsync will be executed on a ThreadPool thread in an asynchronous manner.

2. Task.WaitAll:
Task.WaitAll is a method that blocks the current thread and waits until all the specified Task objects have completed execution. It's used to synchronize and wait for multiple tasks to finish before proceeding with further code execution.
Example usage of Task.WaitAll:
   Task[] tasks = { Task.Run(() => Task1Async()), Task.Run(() => Task2Async()) };
   Task.WaitAll(tasks); // Wait for both Task1Async and Task2Async to complete
In this example, the current thread will wait until both Task1Async and Task2Async have completed before continuing with the subsequent code.

In summary, Task.Run is used to start a new asynchronous task, while Task.WaitAll is used to wait for multiple tasks to complete before proceeding. Task.Run is about starting an asynchronous operation, and Task.WaitAll is about synchronization and waiting for the completion of multiple asynchronous operations.

No comments:

Post a Comment

Hot Topics