0

I need to make an foreach loop with 3 tasks, this needs to wait till all 3 tasks are finish and than move to next one. Something like

foreach (class r in sets) { Task.Factory.StartNew(() => { DoThisFunction1(); }, TaskCreationOptions.LongRunning); Task.Factory.StartNew(() => { DoThisFunction2(); }, TaskCreationOptions.LongRunning); Task.Factory.StartNew(() => { DoThisFunction3(); }, TaskCreationOptions.LongRunning); } 

somebody can give a simple way how to do this?

0

2 Answers 2

5

You can use WaitAll which has no return type and will block simular to Wait on a task or WhenAll which will return an awaitable Task.

Example:

var tasks = new Task[] { Task.Factory.StartNew(() => { DoThisFunction1(); }, TaskCreationOptions.LongRunning), Task.Factory.StartNew(() => { DoThisFunction2(); }, TaskCreationOptions.LongRunning), Task.Factory.StartNew(() => { DoThisFunction3(); }, TaskCreationOptions.LongRunning) }; Task.WaitAll(tasks); // or await Task.WhenAll(tasks); 

A more detailed answer can be found here

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

4 Comments

That simple? Wow, was looking for this quite sometime... thanks!
BTW, this is very low quality answer compared to standard duplicate...
@AlexeiLevenkov Should I improve it according to the sample you provided or does this not matter because this is a dublicate?
@Dr.Fre If you have better answer than already present in the linked duplicate - indeed provide it to the duplicate question, otherwise I don't think it worth your time to improve this one (which by itself is fine, just not much more useful than existing once)
2
class TasksTest { public void Test() { List<string> sets = new List<string> { "set1", "set2", "set3", "set4", }; foreach (var s in sets) { Console.WriteLine("Set {0}", s); var tasks = new[] { Task.Factory.StartNew(() => {DoThisFunction1();}, TaskCreationOptions.LongRunning), Task.Factory.StartNew(() => { DoThisFunction2(); }, TaskCreationOptions.LongRunning), Task.Factory.StartNew(() => { DoThisFunction3(); }, TaskCreationOptions.LongRunning), }; Task.WaitAll(tasks); Console.WriteLine("End Set {0}\n------------", s); } } void DoThisFunction1() { Thread.Sleep(1000); Console.WriteLine("F1"); } void DoThisFunction2() { Thread.Sleep(1500); Console.WriteLine("F2"); } void DoThisFunction3() { Thread.Sleep(2000); Console.WriteLine("F3"); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.