简体   繁体   中英

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.

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.

一旦完成任务,您能否使布尔变为真,然后将其余的放入if(bool)循环中?

Afaik您可以只调用Task.Wait()

Try use this code

task1.Wait();

and read this Task

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM