如何在返回 ValueTask 的 lambda 中使用 Parallel.ForEachAsync 内部返回?

huangapple go评论64阅读模式
英文:

How to return inside a ValueTask returning lambda of Parallel.ForEachAsync?

问题

通常情况下,我们可以在执行的任何分支中等待异步方法调用。其他分支我们可以简单地返回。这不会产生任何警告。

但是当我们在Parallel.ForEachAsync中执行相同操作时,我们会收到警告[CS4014] "因为此调用没有等待,当前方法的执行在调用完成之前继续进行。考虑将 'await' 操作符应用于调用的结果。"

什么是警告在这里的重要性?我们可以忽略这个警告吗?如果不能,如何处理这个警告?

英文:

In general we can await an async method invocation in any one of the Branch of execution. And other branches we can simply return. This will not give any warning.

But when we do the same in Parallel.ForEachAsync, We get the warning CS4014 "Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call."

await method1(null);
IEnumerable<string> collection = new List<string>();

Parallel.ForEachAsync(collection , async (obj, cancelationToken) => {  //this statement gives warning
    if (obj == null)
        return;
    else
        await method2(obj);
});

async ValueTask method1(Object? obj)  //But here there is no warning
{
    if (obj == null)
        return;
    else
        await method2(obj);
}
async Task method2(Object obj)
{
    await Task.Delay(0);
}

What is the significance of warning here? Can we ignore this warning ? If not how to handle this ?

答案1

得分: 3

这个警告与你传递给 ForEachAsync 的 lambda 函数无关,而是与你从 ForEachAsync 返回的值相关。换句话说,这与你是否返回或等待 method2 无关。如果你尝试调用 method1 而没有等待,你会看到相同的警告,因为它返回一个可等待的对象:

method1(null); // 相同的警告

等待对 ForEachAsync 的调用将消除这个警告。

await Parallel.ForEachAsync(collection, async (obj, cancellationToken) =>
{
    if (obj == null)
        return;
    else
        await method2(obj);
});
英文:

That warning doesn't pertain to the lambda you're passing to ForEachAsync: it applies to the value you're returning from ForEachAsync. In other words, it has nothing to do with whether you're returning or awaiting method2. You would see the same warning if you tried invoking method1 without an await, because it returns an awaitable:

method1(null); // same warning

Awaiting the call to ForEachAsync will make the warning go away.

await Parallel.ForEachAsync(collection, async (obj, cancelationToken) =>
{
    if (obj == null)
        return;
    else
        await method2(obj);
});

huangapple
  • 本文由 发表于 2023年4月20日 04:40:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定