gpt4 book ai didi

c# - 在 C# 中启动许多异步任务的语法

转载 作者:可可西里 更新时间:2023-11-01 03:13:39 28 4
gpt4 key购买 nike

我在使用 C# 中的新异步/等待工具时遇到问题。这是我的场景:

static async Task<bool> ManageSomeRemoteTask(int Id, bool flag)
{
var result = await serviceClient.AuthenticateIdAsync(Id);
[... Setup Some Data ...]
await serviceClient.LongAndSlowRemoteCallAsync(Data);
}

static void SendATonOfJunkToSomeWebServiceThatDoesntSupportBatches
{
var myTasks = Dictionary<int, Task<bool>>();
while(IdsLeftToProcess > 0 )
{
Task<bool> t = ManageSomeRemoteTask(Id, true);
myTasks.Add(IdsLeftToProcess ,t);
myTasks[IdsLeftToProcess].Start();
IdsLeftToProcess --;
}

Task.WaitAll(myTasks.Values.ToArray()); //Wait until they are all done
[... Report statistics ...]
}

我有 1 个问题,当我尝试运行它时,我在 Start() 上得到一个 InvalidOperationException 错误消息“Start may not be called on a promise-style task.”这个Google 或 Bing 中似乎没有出现错误消息,所以我不确定这是什么意思。这是我最关心的问题,如何让它运行。我也试过 TaskFactory.StartNew() 但不明白如何以这种方式将参数传递给我的方法。

最佳答案

异步方法返回的任务总是,即它们是在运行状态下创建的。尝试从您的代码中删除 task.Start() - 它应该会修复它。

引自 Stephen Toub's Async/Await FAQ :

Do I need to “Start” Tasks created by methods marked as “async”?

No. Tasks returned from TAP methods are “hot”, meaning the tasks represent operations that are already in-progress. Not only do you not need to call “.Start()” on such tasks, but doing so will fail if you try. For more details, see FAQ on Task.Start.

关于c# - 在 C# 中启动许多异步任务的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11236009/

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