Why Does This Async Action Hang When I Try and Access the Result Property of My Task

Why does this async action hang when I try and access the Result property of my Task?

Yep, that's a deadlock all right. And a common mistake with the TPL, so don't feel bad.

When you write await foo, the runtime, by default, schedules the continuation of the function on the same SynchronizationContext that the method started on. In English, let's say you called your ExecuteAsync from the UI thread. Your query runs on the threadpool thread (because you called Task.Run), but you then await the result. This means that the runtime will schedule your "return result;" line to run back on the UI thread, rather than scheduling it back to the threadpool.

So how does this deadlock? Imagine you just have this code:

var task = dataSource.ExecuteAsync(_ => 42);
var result = task.Result;

So the first line kicks off the asynchronous work. The second line then blocks the UI thread. So when the runtime wants to run the "return result" line back on the UI thread, it can't do that until the Result completes. But of course, the Result can't be given until the return happens. Deadlock.

This illustrates a key rule of using the TPL: when you use .Result on a UI thread (or some other fancy sync context), you must be careful to ensure that nothing that Task is dependent upon is scheduled to the UI thread. Or else evilness happens.

So what do you do? Option #1 is use await everywhere, but as you said that's already not an option. Second option which is available for you is to simply stop using await. You can rewrite your two functions to:

public static Task<T> ExecuteAsync<T>(this OurDBConn dataSource, Func<OurDBConn, T> function)
{
string connectionString = dataSource.ConnectionString;

// Start the SQL and pass back to the caller until finished
return Task.Run(
() =>
{
// Copy the SQL connection so that we don't get two commands running at the same time on the same open connection
using (var ds = new OurDBConn(connectionString))
{
return function(ds);
}
});
}

public static Task<ResultClass> GetTotalAsync( ... )
{
return this.DBConnection.ExecuteAsync<ResultClass>(
ds => ds.Execute("select slow running data into result"));
}

What's the difference? There's now no awaiting anywhere, so nothing being implicitly scheduled to the UI thread. For simple methods like these that have a single return, there's no point in doing an "var result = await...; return result" pattern; just remove the async modifier and pass the task object around directly. It's less overhead, if nothing else.

Option #3 is to specify that you don't want your awaits to schedule back to the UI thread, but just schedule to the thread pool. You do this with the ConfigureAwait method, like so:

public static async Task<ResultClass> GetTotalAsync( ... )
{
var resultTask = this.DBConnection.ExecuteAsync<ResultClass>(
ds => return ds.Execute("select slow running data into result");

return await resultTask.ConfigureAwait(false);
}

Awaiting a task normally would schedule to the UI thread if you're on it; awaiting the result of ContinueAwait will ignore whatever context you are on, and always schedule to the threadpool. The downside of this is you have to sprinkle this everywhere in all functions your .Result depends on, because any missed .ConfigureAwait might be the cause of another deadlock.

Why does this async controller action hang while debugging?

It was related to Application Insights by Microsoft/Azure. I have to look into it a bit more (since I just removed all AI references and I need to re-install to investigate), but it might be an unawaited async call I am making into AI or a bug inside AI (it is pre-release). I am only making three calls into AI manually and I didn't receive any warning about async calls not being awaited, so I do not think this is the case and is probably a bug inside AI or by design.

Uninstalling AI let the exception flow as it normally does.

await' works, but calling task.Result hangs/deadlocks

You're running into the standard deadlock situation that I describe on my blog and in an MSDN article: the async method is attempting to schedule its continuation onto a thread that is being blocked by the call to Result.

In this case, your SynchronizationContext is the one used by NUnit to execute async void test methods. I would try using async Task test methods instead.

Async task hanging


it's a sync method calling this async method, so I call .Wait()

And that's your problem. You're deadlocking because you're blocking on asynchronous code.

The best solution for this is to use await instead of Wait:

await _commService.SendPushNotificationAsync(user.Username, notificationDto.PushContent);

If you absolutely can't use await, then you can try one of the hacks described in my Brownfield Async article.

Why Task stops executing on call any async method if I create it with new Task(action) - .Start() instead of Task.Run()?

The answer is discussed here. Essentially the Task construction takes an Action<> and not a Func<> and so the async delegate is not really being treated as such.

Task bool causes Entity Framework to Hang

As comment by Mick and this post here Asyn-Hanging

I created a deadlock because in my UI thread I was waiting to get Task.Result.

Unity Engine freezes when Accessing Task Token .Result

You need to use the await keyword, something like this:

Token task = await GetElibilityToken(client);

However you need to change the method as well, something like this:

async Task Start()

Actually it's been recommended to use async all the way down always. You can find more information in this topic here.

https://gametorrahod.com/unity-and-async-await/

EDIT: Based on the comments, it seems we are not allowed to change or redefine the Unity's Start to be async Task, so in this case I would still use the async void, despite the fact that it is not been recommended https://docs.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming

async void Start()


Related Topics



Leave a reply



Submit