Click here to Skip to main content
16,002,218 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear,
Is there an equivalent for Java's ExecutorService class in C#?

The following Java code creates a thread pool of a fixed size, and loops over a list of files. Within the loop, the executor executes a worker to process the file (the worker calls a web service).

Java
ExecutorService executor = Executors.newFixedThreadPool(poolSize);

for (int n=0; n < files.length; n++) 
{
    final File myFile = files[n];
    Runnable worker = new MyWorker(myFile);
    executor.execute(worker);
}

try 
{
    executor.shutdown();

    while (!executor.isTerminated()) { }     
} 
finally 
{
    executor.shutdownNow();
}


As i know, in this code, since the pool size is (poolSize), it will start working on (poolSize) jobs and other jobs will be in wait state, as soon as one of the job is finished, another job from the wait queue will be picked up by worker thread and get’s executed. This is explained HERE

I need the same functionality in C#

What I have tried:

This article: Multiple ways how to limit parallel tasks processing seems to explain how to do that in multiple ways but it's not as direct and simple as Java's implementation.
Is there a direct C# implementation of the functionality of ExecutorService ? or should I try longer codes provided by the previous link?

I am not good at threading, so any help is appreciated. Thanks in advance
Posted
Updated 28-Sep-20 10:52am
Comments
Afzaal Ahmad Zeeshan 1-Jan-19 7:33am    
Why can't you use simple threads? Or use the ThreadPool to manage these running operations.
nina4ever 1-Jan-19 8:40am    
can you give me an link to an example how to use ThreadPool of a fixed size ? and will it automatically manage queued tasks ?

Microsoft recommends using Tasks, there is a setting MaxDegreeOfParallelism.
See example here: multithreading - C# Task thread pool - Running 100 tasks across only 10 threads - Stack Overflow[^]
 
Share this answer
 
Comments
nina4ever 1-Jan-19 12:47pm    
thanks. i'll try it and give a feedback
Thanks to RickZeeland. This is a simple working example:

C#
private async void button1_Click(object sender, EventArgs e)
{
    await WriteThem();
    Console.WriteLine("FINISHED ALL in button click");
}

public async Task Write(string s)
{
    for ( int i=0;  i <= 3; i++)
        Console.WriteLine(s.ToUpper() +" - "+ i.ToString().PadLeft(2, '0'));
    await Task.Delay(100);
    Console.WriteLine($"finished {s}");

}
public async Task WriteThem()
{
    Console.WriteLine("started WriteThem");
    await Task.Delay(1000);

    var block = new ActionBlock<string>( async  _ => { await Write(_); } ,
        new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2 });

    List<string> names = new List<string>();
    names.Add("task 01");
    names.Add("task 02");
    names.Add("task 03");
    names.Add("task 04");

    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    try
    {
        foreach (string s in names)
        {
            block.Post(s);
        }

        block.Complete();
        await block.Completion;

        stopwatch.Stop();
        Console.WriteLine("FINISHED in WriteThem: " + stopwatch.Elapsed);

    }
    catch (Exception n)
    {
        Console.WriteLine(n.Message);
    }

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900