我试图按顺序运行这些任务,而不会在 UI 中出现任何阻塞,但是,我已经测试了我找到的所有方法,但仍然遇到问题,当我让任务在没有 UI 阻塞的情况下运行时,我任务中缺少步骤或某些任务无限运行。
public void StartAsync(CancellationToken cancellationToken, string path, int i)
{
var task1 = Task.Run(() => Task1(path, step, i)); //
var task2 = Task.Run(() => Task2(cancellationToken)); // wait for task1 to complete
var task3 = Task.Run(() => Task3(cancellationToken)); // wait for task2 to complete
var task4 = Task.Run(() => Task4(cancellationToken, i)); // will call an external process ) ... wait for task3 to complete
Task.WaitAll(task1, task2, task3, task4);
}
public void AnotherTask()
{
// Some other code ( will call an external process )
}
public void RunAllTasks()
{
int step = 5;
cancellationToken = CancellationToken.None;
string path = "...\\..";
for (int i = 0;i<step;i++)
{
StartAsync(cancellationToken, string path, int i)
}
// wait for StartAsync to complete
AnotherTask();
}
private void button_Click(object sender, RoutedEventArgs e)
{
RunAllTasks();
}
最佳答案
您应该像这样等待每个任务
public async Task StartAsync(CancellationToken cancellationToken, string path, int i)
{
await Task.Run(() => Task1(path, step, i));
await Task.Run(() => Task2(cancellationToken));
await Task.Run(() => Task3(cancellationToken));
await Task.Run(() => Task4(cancellationToken, i));
}
或者也许只是在单个 Task.Run 操作中按顺序调用它们,例如
public Task StartAsync(CancellationToken cancellationToken, string path, int i)
{
return Task.Run(() =>
{
Task1(path, step, i);
Task2(cancellationToken);
Task3(cancellationToken));
Task4(cancellationToken, i);
});
}
并等待 StartAsync 调用,例如
public async Task RunAllTasks()
{
...
for (int i = 0;i < step; i++)
{
await StartAsync(cancellationToken, path, i);
}
...
}
private async void button_Click(object sender, RoutedEventArgs e)
{
await RunAllTasks();
}
如果您想并行多次调用 StartAsync,类似这样的方法也可能有效:
await Task.WhenAll(Enumerable
.Range(0, 5)
.Select(i => StartAsync(cancellationToken, path, i)));
关于c# - 如何在不阻塞 UI 的情况下顺序运行多个任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72954661/