I have a such situtation:
foreach (var item in listBoxFileNames.SelectedItems)
{
MessageBox.Show("I am not waiting");
CancellationTokenSource tokenSourcve = new CancellationTokenSource();
CancellationToken token = tokenSourcve.Token;
Task task1 = new Task(() =>
{
ProcessDatas(); // method
}
, token);
task1.Start();
}
I want to make foreach to wait task’s completion. BUt it is not waiting. It showing me MessageBox immediately after each messagBox.
Yes, you’re starting the task, which will then execute in the background. If you want the loop to behave entirely synchronously, just call
ProcessDatas()not in a task at all. You could start it and then wait for it to finish – but it’s not clear what benefit that would give you.If you want to start all the tasks in parallel, but then wait for them afterwards, you could create a
List<Task>and then callTask.WaitAll– or just useParallel.ForEachto start with.