Preventing a deadlock when calling an async method without using await

I need to call a method returning a Task from within

public override void OnActionExecuting(ActionExecutingContext filterContext)

It wont let me make this method async it throws the following

An asynchronous module or handler completed while an asynchronous
operation was still pending.

and when calling

 entityStorage.GetCurrentUser().Result

I get a deadlock. How can I avoid this?

I have been playing around with it coming up with stuff like

entityStorage.GetCurrentUser().Result.ConfigureAwait(false).GetAwaiter().GetResult();

But this isn’t working. How can I do it? My solution will need to work with ASP.NET 4 and the Async Targetting Pack, I can’t use ASP.NET 4.5 as am deploying to Azure.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The cause of the deadlock is explained here. In short, don’t block on async code. You should use ConfigureAwait(false) in your library async code and await the results (not use Result or Wait).

Update: Please vote here for the MVC team to add support for async action filters.

Method 2

Since await is just syntax sugar for the compiler rewriting a continuation for you, the most ‘direct’ path would be to take whatever code was going to follow your await and make it a ContinueWith call.

So, something like:

entityStorage.GetCurrentUser().ContinueWith(t =>
{
    // do your other stuff here
});

Method 3

If you MUST convert asynch to synch.

public User GetCurrentUserSynch()
    {
        return Task.Run(() =>
        {
            var asyncResult = entityStorage.GetCurrentUser();
            while (!asyncResult.IsCompleted)
            {
                Application.Current.TryFindResource(new object()); // This is for WPF but you can do some other nonsense action of your choosing
            }

            return asyncResult.Result;
        }).Result;
    }

Otherwise use @Stephen’s answer.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x