Reputation: 1226
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.
Upvotes: 1
Views: 7455
Reputation: 198
Can't you make a Bool that becomes true once the task is done then put the rest in a if (bool) loop?
Upvotes: 1
Reputation: 1500145
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 call Task.WaitAll
- or just use Parallel.ForEach
to start with.
Upvotes: 9