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?
The correct way to call a
ValueTaskmethod 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:
.AsTask()always. The reason whyValueTaskexists is so that a newTaskobject does not need to be allocated if the method completes synchronously. But here, you're creating aTaskanyway, invalidating the benefit of usingValueTask..Result, which will lock the current thread until theTaskcompletes, invalidating the benefit of using async code and potentially introducing the possibility of deadlocks. See the article Don't Block on Async CodeThe 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.