gpt4 book ai didi

c# - 无法将类型 'void' 隐式转换为 'System.Threading.Tasks.Task'

转载 作者:太空狗 更新时间:2023-10-30 00:24:12 36 4
gpt4 key购买 nike

下面是我的代码的简化版本,它会生成以下编译错误

Cannot implicitly convert type 'void' to 'System.Threading.Tasks.Task'

在这种情况下,GetDataAsync 方法不需要返回任何内容。我怎样才能让它返回一个我可以等待的任务?

static async void Run()
{
List<string> IDs = new List<string>() { "a", "b", "c", "d", "e", "f" };
Task[] tasks = new Task[IDs.Count];
for (int i = 0; i < IDs.Count; i++)
tasks[i] = await GetDataAsync(IDs[i]);

Task.WaitAll(tasks);
}

async static Task GetDataAsync(string id)
{
var data = await Task.Run(() => GetDataSynchronous(id));
// some other logic to display data in ui
}

最佳答案

由于您试图存储对 GetDataAsync 的所有调用的结果哪些是任务,您不应该等待它们。只需删除 await , 收集所有任务并在最后等待他们。

static void Run()
{
List<string> IDs = new List<string>() { "a", "b", "c", "d", "e", "f" };
Task[] tasks = new Task[IDs.Count];
for (int i = 0; i < IDs.Count; i++)
tasks[i] = GetDataAsync(IDs[i]);

Task.WaitAll(tasks);
}

另外,没有必要制作 Run完全不异步(尤其不是 async void,它应该只用于 UI 事件处理程序),因为您正在与 Task.WaitAll 同步等待.

如果你想异步等待然后制作Run async void (仅当它是 UI 事件处理程序时)并使用 Task.WhenAll(tasks)一起等待所有任务:

static async void Run()
{
await Task.WhenAll(new[] {"a", "b", "c", "d", "e", "f"}.Select(GetDataAsync));
}

关于c# - 无法将类型 'void' 隐式转换为 'System.Threading.Tasks.Task',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28005498/

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