Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my async function hanging when calling task.run function

I want to make a function async since I'd like to return the results to the UI and don't want to make this hang, but it is anyway.

Can someone tell me why this would be hanging?

public ActionResult Index()
{
    return View(FunctionThreeAsync().Result);
}

private async Task<MyType> FunctionThreeAsync()
{
    return await FunctionThree();
}

private Task<MyType> FunctionThree()
{
    return Task.Run<MyType>(() => { /* code */ });
}
like image 718
J Hunt Avatar asked Feb 09 '23 14:02

J Hunt


1 Answers

This:

return View(FunctionThreeAsync().Result);

Is deadlocking your code. You shouldn't be blocking on an async method. Instead, mark your method as async, make it return a Task<T> and await the call:

public async Task<ActionResult> DoStuffAsync()
{
    return View(await FunctionThreeAsync());
}

Async goes all the way. When you have a method that's async, it will need to be asynchronously waited on, not synchronously blocked on. This means spreading async throughout your code base.

like image 114
Yuval Itzchakov Avatar answered Feb 12 '23 12:02

Yuval Itzchakov