Search code examples
c#async-awaittask

Refactoring explicitly created Tasks, where method calls now have an async operation, creates compiler warning


I'm refactoring code from our .NET Framework library into a microservice. The microservice has a repository that has an async method to get data from a stored procedure. However, the old code's methods don't use an async method to get this same data and the calls (from legacy code) to these methods look like this:

Task appsSubmittedTask = new Task(
    () => { Method1(otherData, dashboardData, reportData); });

Task assistancePendingTask = new Task(
    () => { Method2(otherData, dashboardData, reportData); });

Task assistanceDeniedTask = new Task(
    () => { Method3(otherData, dashboardData, reportData); });

appsSubmittedTask.Start();
assistancePendingTask.Start();
assistanceDeniedTask.Start();

Task.WaitAll(appsSubmittedTask, assistancePendingTask, assistanceDeniedTask);

Each of the three methods (Method1, Method2, Method3) in the original code returned void. Now that the new methods in the microservice are accessing an injected service for stored procedure calls which is asynchronous I updated the three methods to have async Task in the method signature, each method now has data access like this:

IList<resultType> results = await _service.AsyncStoredProcedureMethod(...params)

So now the above methods being called by the three created Tasks have squiggles underneath the method call with the "because the call is not awaited, execution of the current method continues before the call is completed"

Is there a specific way to go about this where I'm not spinning up the three Tasks, as I'm worried that ignoring the warning and running the old code (with three tasks) may cause the underlying DbContexts from the _service to overlap? Or should I create a stored procedure call in the _service that isn't asynchronous? I'm open to any ideas.


Solution

  • You will need to chain the async and await in all methods now, otherwise the results will be unexpected and inconsistent.

    One of the solution could be to await your method call in the Task objects you created like below:

    Task appsSubmittedTask = new Task(async () => { await Method1(context, dashboardData, reportData); });
    Task assistancePendingTask = new Task(async () => { await Method2(context, dashboardData, reportData); });
    Task assistanceDeniedTask = new Task(async () => { await Method3(context, dashboardData, reportData); });
    

    Please also note that using the Task contructor is not the good approach to be used and we used Task.Start() method for this purpose. You can refer to the following post for more details: Await new Task<T>( ... ) : Task does not run?