Ogan Tabanlı
Ogan Tabanlı

Reputation: 209

C# Threads Multiple Queue

I have a for loop it's looping about 500 times. On each iteration, it calls a method and that takes about 1 minute. As such, I have to wait 500 minutes. It's very long time.

I want to get this to work using threads but when I create 500 threads at the same time, I'm getting an exception.

I think I need to use "Queue Threads". For example, start 10 threads and when one finishes then start a new one. That way, there's always 10 threads working at the same time -- no less, no more.

Is this possible?

Upvotes: 0

Views: 89

Answers (2)

Puddler
Puddler

Reputation: 2939

You are going to need to be more specific about your needs but something like a Parallel.ForEach might help as it manages the number of threads for you.

For example:

static void Main(string[] args)
{
    List<string> stringList = new List<string>();
    stringList.Add("A");
    stringList.Add("B");
    stringList.Add("C");

    Parallel.ForEach(stringList, aString =>
        {
            Console.WriteLine(aString);
        });

    Console.WriteLine("Hello");
}

Upvotes: 0

KnightFox
KnightFox

Reputation: 3252

If you do not care about the order in which the method is executed, you could try using async programming and creating Tasks for each loop and waiting for them to finish.

     void Main()
     {
        var tasks = Enumerable.Range(0, 500).Select(e =>    System.Threading.Tasks.Task.Run(() => DoWork(e)));
         System.Threading.Tasks.Task.WaitAll(tasks.ToArray());
     }

     public void DoWork(int i)
     {
         Console.WriteLine(i.ToString());
     }

If you want to limit the number of task that are run parallely, you could run a for loop, create tasks in a batch and wait for them to finish before moving to the next batch.

Upvotes: 1

Related Questions