gpt4 book ai didi

c# - 等待异步操作

转载 作者:行者123 更新时间:2023-11-30 20:28:31 25 4
gpt4 key购买 nike

我有一个静态泛型方法,旨在并行地对集合执行操作(不用担心节流;我已经解决了这个问题;这里的代码是精简版):

public static IEnumerable<Task> RunAllAsync<T>(this IEnumerable<T> enumerable, Action<T> action)
{
var tasks = new List<Task>();
foreach (var t in enumerable)
{
tasks.Add(Task.Run(() => action(t)));
}
return tasks;
}

这是一个用法示例:

public async Task UsageSync()
{
var numbers = Enumerable.Range(1, 5);
var random = new Random();
var tasks = numbers.RunAllAsync(i =>
{
Console.WriteLine($"A {i}");
Thread.Sleep(random.Next(1000));
Console.WriteLine($"B {i}");
});
Console.WriteLine("Awaiting end");
await Task.WhenAll(tasks.ToArray());
Console.WriteLine("awaited");
Thread.Sleep(2000);
Console.WriteLine("Finished");
}

输出:

Awaiting end
A 4
A 5
A 1
A 2
A 3
B 3
B 2
B 1
B 5
B 4
awaited
Finished

一切如预期。但现在我们使该操作本身成为一个异步委托(delegate):

public async Task UsageAsync()
{
var numbers = Enumerable.Range(1, 5);
var random = new Random();
var tasks = numbers.RunAllAsync(async i =>
{
Console.WriteLine($"A {i}");
await Task.Run(() =>
{
Console.WriteLine($"B {i}");
Thread.Sleep(random.Next(1000));
Console.WriteLine($"C {i}");
});
});
Console.WriteLine("Awaiting end");
await Task.WhenAll(tasks.ToArray());
Console.WriteLine("awaited");
Thread.Sleep(2000);
Console.WriteLine("Finished");
}

输出:

Awaiting end
A 4
B 4
A 1
A 5
A 3
A 2
B 2
awaited
B 5
B 1
B 3
C 3
C 2
C 1
C 5
C 4
Finished

看到了吗?该方法在线程完成之前达到“等待”状态!

我应该怎么做才能确保等待异步操作?

最佳答案

由于您正在处理 Action<T> , async i => { ... }被翻译成 async void方法。 async void设计使它不可能等待它完成。将您的参数更改为 Func<T, Task> func并更改调用 action(t)await func(t) .

关于c# - 等待异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47205978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com