Ezio Auditore da Firenze
Ezio Auditore da Firenze

Reputation: 1226

Foreach wait for task to complete

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

Answers (4)

Charp
Charp

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

Jon Skeet
Jon Skeet

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

Likurg
Likurg

Reputation: 2760

Try use this code

task1.Wait();

and read this Task

Upvotes: 0

Boas Enkler
Boas Enkler

Reputation: 12557

Afaik you can just call the Task.Wait()

Upvotes: 0

Related Questions