Home > DeveloperSection > Forums > Creating a task inside a foreach loop
Jeet Verma
Jeet Verma

Total Post:110

Posted on    August-14-2014 5:08 AM

 C# C# 

 1 Reply(s)
 1084  View(s)
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)




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?


Pravesh Singh

Total Post:412

Posted on    August-14-2014 6:51 AM

hi Jeet, 
You can try this:

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

Don't want to miss updates? Please click the below button!

Follow MindStick