任务链(等待previous任务完成) [英] Task chaining (wait for the previous task to completed)

查看:166
本文介绍了任务链(等待previous任务完成)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var tasks = new List<Task>();

foreach (var guid in guids)
{
    var task = new Task( ...);
    tasks.Add(task);
}

foreach (var task in tasks)
{
    task.Start();
    Task.WaitAll(task);
}

这是运行在UI线程。我需要在任务执行的所有任务后,其他变量之一。问题是,如果我叫Task.WaitAll(任务),用户界面​​冻结。我该怎么办下面的逻辑,而无需用户界面冻结?

This is run of the UI thread. I need to execute all tasks in tasks variable one after the other. The problem is if I call Task.WaitAll(task), the UI freeze. How can I do the following logic without having the UI freeze?

推荐答案

这是不是任务链接。

您需要做的使用 ContinueWith 任务链。最后的任务将需要更新的用户界面。

You need to do Task chaining using ContinueWith. Last task would need to update the UI.

Task.Factory.StartNew( () => DoThis())
   .ContinueWith((t1) => DoThat())
   .ContinueWith((t2) => UpdateUi(), 
       TaskScheduler.FromCurrentSynchronizationContext());

注意的最后一行 TaskScheduler.FromCurrentSynchronizationContext()这将确保任务将在同步方面(UI线程)上运行。

Note the last line has TaskScheduler.FromCurrentSynchronizationContext() this will ensure task will run in the synchronization context (UI Thread).

这篇关于任务链(等待previous任务完成)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆