Search code examples
c#asynchronous.net-7.0valuetaskparallel.foreachasync

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


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 ?


Solution

  • 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);
    });