CREATING A TASK INSIDE A FOREACH LOOP

Jeet Verma

Total Post:110

Points:776
Posted by  Jeet Verma
C# 
C#
 1111  View(s)
Ratings:
Rate this:

I have a typical foreach loop that calls a method where the parameter is an element of the collection we're looping over; something like this:

foreach (byte x in SomeCollection)

{

   SomeMethod(x);

}

The problem is that SomeMethod takes a long time to run. I want to move the call into a new task so that the loop just creates the tasks and then the thread that called the loops just continues. How do I do this in a thread-safe way?

Thanks.

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Creating a task inside a foreach loop

    hi Jeet, 

    You can try this:

    foreach (byte x in SomeCollection) { Task.Factory.StartNew(() => SomeMethod(x)); }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!