且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何等待所有任务完成而不会阻塞UI线程?

更新时间:2021-09-17 22:17:20

首先,我将安装现在,使用这个问题的答案,您可以异步注册进程退出,而无需使用 Task.Factory.StartNew :

Now, using the answer to this question, you can asynchronously register for process exit, with no need to use 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;
    }
}

现在,您可以执行以下操作:

Now, you can do this:

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;