Reputation: 337
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
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:
.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
..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 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.
Upvotes: 3