Saurabh Soni
Saurabh Soni

Reputation: 337

Calling ValueTask method from the non async method in ASP.NET Core?

I have created a ValueTask type of method in ASP.NET Core:

private async ValueTask<InterceptionResult<int>> SaveChanges(DbContext eventData, InterceptionResult<int> result)
{
    await .... my Code
    return result;
}

I am calling this method from a non-async process:

public override MyMethod<int> SavingChanges(DbContext eventData, InterceptionResult<int> result)
{
    var interceptionResult = SaveChanges(eventData, result).AsTask();
    return interceptionResult.Result;
}

Can you please suggest the correct way of calling the ValueTask method from the non-async process in ASP.NET Core?

Upvotes: 0

Views: 771

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40998

The correct way to call a ValueTask method from a non-async method is to not to. Just don't do it.

The way you are trying to do it is not good, for two reasons:

  1. You're calling .AsTask() always. The reason why ValueTask exists is so that a new Task object does not need to be allocated if the method completes synchronously. But here, you're creating a Task anyway, invalidating the benefit of using ValueTask.
  2. You're using .Result, which will lock the current thread until the Task completes, invalidating the benefit of using async code and potentially introducing the possibility of deadlocks. See the article Don't Block on Async Code

The correct way is to create a second version that is completely synchronous and call that from SavingChanges. This is what Microsoft does when they expose a synchronous and asynchronous version of methods. They don't just call the async version from the synchronous.

Upvotes: 3

Related Questions