在下面的代码中,我在处理任务之前禁用按钮,并希望在所有任务完成后启用它。
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 线程。如何等到所有任务完成然后启用该按钮?
首先,我要安装Microsoft.Bcl.Async这将使得能够使用async-await
在.NET 4.0 中。
现在,使用答案这个问题,可以异步注册进程退出,无需使用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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)