简体   繁体   中英

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 */ });
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM