We had a developer who had to add async
keywords to accomodate changes he made to a microservice we run. Basically, at the highest level our controller is calling a specific method that runs a Parallel.Foeach call that looks like this:
Parallel.ForEach(formGroupIds, new ParallelOptions() { MaxDegreeOfParallelism = 4 }, async formGroupId =>
{
DataTable dtCases = await methodCalled;
certainDictionary[formGroupId] = dtCases;
});
This code threw the following exception:
Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>.
This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.
The awaited method returns a Task<DataTable>
so it's not an async void
. To fix this, in the method that the above code is called and the controller that calls it, I added the async
keyword with the appropriate Task<type>
and the error went away.
However, the method that calls the Parallel.Foreach
has the green squiggle underneath the method name with the warning "This async method lacks 'await' operators and will run synchronously.."
We use SonarCloud for our PRs, and it's causing a code smell. Is there something else more appropriate to be done, or is this something that can be ignored?