0

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?

1
  • "getting Exception" does not clarify problem (nor shows code you have exception in)... So please try to show code you've tried (preferably edited to be small sample directly related to your goal AND exception) and have problem with, make sure to post exact error message. Commented Jul 30, 2015 at 2:00

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.