Home > Backend Development > C++ > How Can I Execute Multiple Tasks Concurrently with a Limited Number of Threads Using C#?

How Can I Execute Multiple Tasks Concurrently with a Limited Number of Threads Using C#?

Susan Sarandon
Release: 2025-01-02 15:08:38
Original
616 people have browsed it

How Can I Execute Multiple Tasks Concurrently with a Limited Number of Threads Using C#?

Executing Tasks Concurrently with Limited Threads

Problem:

Suppose you have a set of tasks that must be executed sequentially, with only a maximum of X tasks running at a time. Traditionally, ThreadPool.QueueUserWorkItem() was used for such tasks, but it is now considered a suboptimal approach.

Solution Using Tasks:

To achieve this concurrency limitation using Tasks, we can employ a SemaphoreSlim object to manage the number of threads available. Here's a code snippet demonstrating the approach:

SemaphoreSlim maxThread = new SemaphoreSlim(10);

for (int i = 0; i < 115; i++)
{
    maxThread.Wait();
    Task.Factory.StartNew(() =>
        {
            // Your task implementation
        }, TaskCreationOptions.LongRunning)
    .ContinueWith((task) => maxThread.Release());
}
Copy after login

Here's how the code works:

  • SemaphoreSlim Initialization: A SemaphoreSlim is initialized with a maximum thread count of 10, which allows up to 10 tasks to run concurrently.
  • Task Execution: For each task to be executed, the Wait() method of the semaphore is called, which blocks until a thread becomes available. Once a thread is free, a new task is started using Task.Factory.StartNew().
  • Task Completion: After each task completes, the ContinueWith() method attached to the task releases the thread used by calling the Release() method of the semaphore.
  • Sequential Execution: Because of the limited thread availability enforced by the semaphore, tasks are executed sequentially, with a maximum of 10 tasks running at any given time.

The above is the detailed content of How Can I Execute Multiple Tasks Concurrently with a Limited Number of Threads Using C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template