任务链(等待previous任务完成)任务、previous

2023-09-04 00:08:02 作者:泪未流心先碎

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).