【问题标题】:How to wait until all tasks finished without blocking UI thread?如何在不阻塞 UI 线程的情况下等到所有任务完成?
【发布时间】:2015-12-07 16:54:03
【问题描述】:

在以下代码中,我在处理任务之前禁用按钮,并希望在所有任务完成后启用它。

List<Task> tasks = new List<Task>();
buttonUpdateImage.Enabled = false; // disable button
foreach (OLVListItem item in cellsListView.CheckedItems)
{
    Cell c = (Cell)(item.RowObject);

    var task = Task.Factory.StartNew(() =>
    {
        Process p = new Process();
        ...
        p.Start();
        p.WaitForExit();
    });
    task.ContinueWith(t => c.Status = 0);
    tasks.Add(task);
}

Task.WaitAll(tasks.ToArray());
// enable button here

WaitAll 正在阻塞 UI 线程。如何等到所有任务完成后再启用按钮?

【问题讨论】:

  • 如果您使用 .Net 框架 >= 4.0 为什么不使用 async> 和 await 组合?我认为它可以解决您的问题:)
  • 你使用的是哪个框架版本?
  • @Yuval Itzchakov: 4.0
  • 而不是 Task.WaitAll Task.WhenAll(tasks,i=> myCompletionAction)

标签: c# winforms task-parallel-library task


【解决方案1】:

首先,我将安装 Microsoft.Bcl.Async,这将允许在 .NET 4.0 中使用 async-await。

现在,使用this question的答案,您可以异步注册进程退出,无需使用Task.Factory.StartNew:

public static class ProcessExtensions
{
    public static Task RunProcessAsync(this Process process, string fileName)
    {
        if (process == null)
            throw new ArgumentNullException(nameof(process));

        var tcs = new TaskCompletionSource<bool>();
        process.StartInfo = new ProcessStartInfo
        {
            FileName = fileName 
        };

        process.EnableRaisingEvents = true
        process.Exited += (sender, args) =>
        {
            tcs.SetResult(true);
            process.Dispose();
        };

        process.Start();
        return tcs.Task;
    }
}

现在,你可以这样做了:

buttonUpdateImage.Enabled = false; // disable button

var tasks = cellsListView.CheckedItems.Cast<OLVListItem>()
                                      .Select(async item => 
{
    Cell cell = (Cell)item.RowObject;

    var process = new Process();
    await process.RunProcessAsync("path");

    cell.Status = 0;
});

await Task.WhenAll(tasks);
buttonUpdateImage.Enabled = true;

【讨论】:

  • 抱歉,ProcessUtils 是什么?谷歌搜索会导致模棱两可的结果。我知道 RunProcessAsync 是ProcessUtils的扩展?
  • @Pablo 编辑了我的代码以使其清晰。我已经把它变成了一个扩展方法,而不是原来的实用方法。
【解决方案2】:
List<Task> tasks = new List<Task>();
buttonUpdateImage.Enabled = false; // disable button
foreach (OLVListItem item in cellsListView.CheckedItems)
{
    Cell c = (Cell)(item.RowObject);

    var task = Task.Factory.StartNew(() =>
    {
        Process p = new Process();
        ...
        p.Start();
        p.WaitForExit();
    }).ContinueWith(t => c.Status = 0); // this modification is very important, Please note it, this will fix a problem

    tasks.Add(task);
}

// your code has been modified to just make the task object 
// is the continued task instead of the task is the original task 
// Task.WaitAll and add this instead of it.
Task.Factory.ContinueWhenAll(tasks.ToArray(), ac => buttonUpdateImage.Enabled = true;);    

另一种方式.....

// Note this object.
Barrier b = new Barrier(cellsListView.CheckedItems.Count, () => {
   // enable the button here
   buttonUpdateImage.Enabled = true;
});

buttonUpdateImage.Enabled = false; // disable button
foreach (OLVListItem item in cellsListView.CheckedItems)
{
    Cell c = (Cell)(item.RowObject);

    var task = Task.Factory.StartNew(() =>
    {
          Process p = new Process();
            ...
          p.Start();
          p.WaitForExit();             
     }).ContinueWith(t => {
          c.Status = 0;
          b.SignalAndWait();
     });
}

第一种比第二种好,我建议你使用第一种。

【讨论】:

  • 将任务添加到任务集合并运行集合是鼓舞人心的
【解决方案3】:

你可以新建一个任务来运行WaitAll方法,就像

Task.Factory.StartNew(() =>
{
    Task.WaitAll(tasks.ToArray());
    Action act = () =>
    {
        this.button1.Enabled = true;
    };
    this.button1.Invoke(act);
});

【讨论】:

  • 在一个任务中同时进行阻塞操作和 UI 访问操作是个好主意吗?如果它在 Threadpool 中运行,那么访问 UI 可能会导致它崩溃。如果它在 UI 线程中运行,那么它将被阻塞。除非我错过了什么……
  • @Pablo 是的,它们在不同的线程上工作,所以我们需要使用Invoke 方法
猜你喜欢
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多