514

I was recently reading some code that uses a lot of async methods, but then sometimes needs to execute them synchronously. The code does:

Foo foo = GetFooAsync(...).GetAwaiter().GetResult();

Is this the same as

Foo foo = GetFooAsync(...).Result;
5
  • 9
    From the docs of GetResult: "This type and its members are intended for use by the compiler." Other person shouldn't be using it.
    – spender
    Jun 24, 2013 at 20:31
  • 47
    This is called "sync over async", and unless you know how the task is implemented can be a really bad idea. It can instantly deadlock in many cases (an async/await method in MVC, for example) Jun 24, 2013 at 20:35
  • 12
    Don't Block on Async Code
    – I4V
    Jun 24, 2013 at 21:08
  • 85
    In the real world, we have constructors, we have "no await" interfaces we need to implement, and we are given async methods everywhere. I would be pleased to use something that just works without I have to wonder why it is "dangerous", "not to be used" or "avoid at all costs". Every single time I have to mess with async turn out to a headache.
    – Larry
    Oct 22, 2019 at 7:26
  • Totally agree Larry. I'm calling a new async microservice from my monolith and using async/await everywhere means I have to update 100+ files. Quite a headache.
    – wilmol
    Nov 22, 2022 at 3:43

7 Answers 7

279

Task.GetAwaiter().GetResult() is preferred over Task.Wait and Task.Result because it propagates exceptions rather than wrapping them in an AggregateException. However, all three methods cause the potential for deadlock and thread pool starvation issues. They should all be avoided in favor of async/await.

The quote below explains why Task.Wait and Task.Result don't simply contain the exception propagation behavior of Task.GetAwaiter().GetResult() (due to a "very high compatibility bar").

As I mentioned previously, we have a very high compatibility bar, and thus we’ve avoided breaking changes. As such, Task.Wait retains its original behavior of always wrapping. However, you may find yourself in some advanced situations where you want behavior similar to the synchronous blocking employed by Task.Wait, but where you want the original exception propagated unwrapped rather than it being encased in an AggregateException. To achieve that, you can target the Task’s awaiter directly. When you write “await task;”, the compiler translates that into usage of the Task.GetAwaiter() method, which returns an instance that has a GetResult() method. When used on a faulted Task, GetResult() will propagate the original exception (this is how “await task;” gets its behavior). You can thus use “task.GetAwaiter().GetResult()” if you want to directly invoke this propagation logic.

https://devblogs.microsoft.com/pfxteam/task-exception-handling-in-net-4-5/

GetResult” actually means “check the task for errors”

In general, I try my best to avoid synchronously blocking on an asynchronous task. However, there are a handful of situations where I do violate that guideline. In those rare conditions, my preferred method is GetAwaiter().GetResult() because it preserves the task exceptions instead of wrapping them in an AggregateException.

https://blog.stephencleary.com/2014/12/a-tour-of-task-part-6-results.html

10
  • 4
    So basically Task.GetAwaiter().GetResult() is equivalent to await task. I assume the first option is used when the method cannot be marked with async(constructor for instance). Is that correct? If yes, then it collides with the top answer @It'sNotALie
    – OlegI
    Oct 11, 2018 at 19:44
  • 10
    @OlegI: Task.GetAwaiter().GetResult() is more equivalent to Task.Wait and Task.Result (in that all three will block synchronously and have the potential for deadlocks), but Task.GetAwaiter().GetResult() has the exception propagation behavior of await task. Oct 12, 2018 at 13:01
  • 5
    @DanielLorenz: See the following quote: "Using ConfigureAwait(false) to avoid deadlocks is a dangerous practice. You would have to use ConfigureAwait(false) for every await in the transitive closure of all methods called by the blocking code, including all third- and second-party code. Using ConfigureAwait(false) to avoid deadlock is at best just a hack). ... the better solution is “Don’t block on async code”." - blog.stephencleary.com/2012/07/dont-block-on-async-code.html Dec 3, 2018 at 2:30
  • 19
    I don't get it. Task.Wait and Task.Result are broken by design? Why aren't they made obsolete?
    – osexpert
    Dec 26, 2018 at 23:37
  • 2
    @ScottyMacDev IMO you answered your own question. Sometimes you just can't follow the "best practices". Just be aware of the pitfalls. Consider using continuations with ContinueWith() instead of GetAwaiter().GetResult(). If you need to capture the context you can set TaskScheduler.FromCurrentSynchronizationContext() as a parameter.
    – Rev
    Oct 18, 2022 at 11:53
245

EDIT: This was written when I was 13, and is out of date. I recommend Nitin Agarwal's answer instead.

Pretty much. One small difference though: if the Task fails, GetResult() will just throw the exception caused directly, while Task.Result will throw an AggregateException. However, what's the point of using either of those when it's async? The 100x better option is to use await.

Also, you're not meant to use GetResult(). It's meant to be for compiler use only, not for you. But if you don't want the annoying AggregateException, use it.

17
  • 28
    @JayBazuzi Not if your unit testing framework supports async unit tests, which I think newest versions of most frameworks do.
    – svick
    Jun 24, 2013 at 20:52
  • 15
    @JayBazuzi: MSTest, xUnit, and NUnit all support async Task unit tests, and have for some time now. Jun 24, 2013 at 22:18
  • 29
    pushing back on the 100x - it's 1000x worse to use await if you're adapting old code and using await requires a rewrite.
    – stuck
    Jun 18, 2016 at 17:59
  • 17
    @AlexZhukovskiy: I disagree. Jul 29, 2016 at 13:53
  • 95
    The 100x better option is to use await. I hate statements like this, if I could slap await in front of it I would. But, when I'm trying to get async code to work against non-async code like what frequently happens to me a lot in Xamarin, I end up having to use things like ContinueWith a lot in order to make it not deadlock the UI. Edit: I know this is old, but that doesn't alleviate my frustration finding answers that state this with no alternatives for situations where you can't just use await.
    – Thomas F.
    Jun 18, 2018 at 13:19
76

https://github.com/aspnet/Security/issues/59

"One last remark: you should avoid using Task.Result and Task.Wait as much as possible as they always encapsulate the inner exception in an AggregateException and replace the message by a generic one (One or more errors occurred), which makes debugging harder. Even if the synchronous version shouldn't be used that often, you should strongly consider using Task.GetAwaiter().GetResult() instead."

4
  • 23
    The source referenced here is someone quoting someone else, without a reference. Consider context: I can see lots of people blindly using GetAwaiter().GetResult() everywhere after reading this. Oct 27, 2016 at 1:35
  • 2
    So we shouldn't use it?
    – tofutim
    Feb 17, 2017 at 22:23
  • 17
    If two tasks end with an exception you will loose the second one in this scenario Task.WhenAll(task1, task2).GetAwaiter().GetResult();.
    – Monsignor
    Aug 11, 2017 at 7:53
  • 1
    Here's another example: github.com/aspnet/AspNetCore/issues/13611 Sep 4, 2019 at 14:48
47

Another difference is when async function returns just Task instead of Task<T> then you cannot use

GetFooAsync(...).Result;

Whereas

GetFooAsync(...).GetAwaiter().GetResult();

still works.

I know the example code in the question is for the case Task<T>, however the question is asked generally.

4
  • 1
    This is not true. Check out my fiddle which uses exactly this construct: dotnetfiddle.net/B4ewH8 Jan 23, 2018 at 14:26
  • 5
    @wojciech_rak In your code, you are using Result with GetIntAsync() which returns Task<int> not just Task. I suggest you to read my answer again. Jan 23, 2018 at 23:33
  • 2
    You're right, at first I understood you answer that you can't GetFooAsync(...).Result inside a function that returns Task. This now makes sense, since there are no void Properties in C# (Task.Result is a property), but you can of course call a void method. Jan 24, 2018 at 14:02
  • 1
    The Task is not returning a value so we expect .Result to be an error. The fact that task.GetAwaiter().GetResult() still works is counter-intuitive and deserves a little emphasis.
    – H2ONaCl
    Jan 30, 2021 at 5:26
33

As already mentioned if you can use await. If you need to run the code synchronously like you mention .GetAwaiter().GetResult(), .Result or .Wait() is a risk for deadlocks as many have said in comments/answers. Since most of us like oneliners you can use these for .Net 4.5<

Acquiring a value via an async method:

var result = Task.Run(() => asyncGetValue()).Result;

Syncronously calling an async method

Task.Run(() => asyncMethod()).Wait();

No deadlock issues will occur due to the use of Task.Run.

Source:

https://stackoverflow.com/a/32429753/3850405

Update:

Could cause a deadlock if the calling thread is from the threadpool. The following happens: A new task is queued to the end of the queue, and the threadpool thread which would eventually execute the Task is blocked until the Task is executed.

Source:

https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d

3
  • If you vote down, please say why. Hard to improve answers otherwise.
    – Ogglas
    Dec 30, 2020 at 23:51
  • 2
    Why does it prevent a deadlock? I realize that Task.Run offloads the work to ThreadPool, but we're still waiting on this thread for that work to finish.
    – Mike
    Feb 8, 2021 at 8:47
  • 1
    @Mike The problem with using only .Result or .Wait() is that if you block the threads which are supposed to work on the Tasks, then there won’t be a thread to complete a Task. You can read more about it here: medium.com/rubrikkgroup/…
    – Ogglas
    Feb 8, 2021 at 9:17
21

I checked the source code of TaskOfResult.cs (Source code of TaskOfResult.cs):

If Task is not completed, Task.Result will call Task.Wait() method in getter.

public TResult Result
{
    get
    {
        // If the result has not been calculated yet, wait for it.
        if (!IsCompleted)
        {
            // We call NOCTD for two reasons: 
            //    1. If the task runs on another thread, then we definitely need to notify that thread-slipping is required.
            //    2. If the task runs inline but takes some time to complete, it will suffer ThreadAbort with possible state corruption.
            //         - it is best to prevent this unless the user explicitly asks to view the value with thread-slipping enabled.
            //#if !PFX_LEGACY_3_5
            //                    Debugger.NotifyOfCrossThreadDependency();  
            //#endif
            Wait();
        }

        // Throw an exception if appropriate.
        ThrowIfExceptional(!m_resultWasSet);

        // We shouldn't be here if the result has not been set.
        Contract.Assert(m_resultWasSet, "Task<T>.Result getter: Expected result to have been set.");

        return m_result;
    }
    internal set
    {
        Contract.Assert(m_valueSelector == null, "Task<T>.Result_set: m_valueSelector != null");

        if (!TrySetResult(value))
        {
            throw new InvalidOperationException(Strings.TaskT_TransitionToFinal_AlreadyCompleted);
        }
    }
}

If we call the GetAwaiter method of Task, Task will wrapped TaskAwaiter<TResult> (Source code of GetAwaiter()), (Source code of TaskAwaiter) :

public TaskAwaiter GetAwaiter()
{
    return new TaskAwaiter(this);
}

And if we call the GetResult() method of TaskAwaiter<TResult>, it will call Task.Result property, that Task.Result will call Wait() method of Task ( Source code of GetResult()):

public TResult GetResult()
{
    TaskAwaiter.ValidateEnd(m_task);
    return m_task.Result;
}

It is source code of ValidateEnd(Task task) ( Source code of ValidateEnd(Task task) ):

internal static void ValidateEnd(Task task)
{
    if (task.Status != TaskStatus.RanToCompletion)
         HandleNonSuccess(task);
}

private static void HandleNonSuccess(Task task)
{
    if (!task.IsCompleted)
    {
        try { task.Wait(); }
        catch { }
    }
    if (task.Status != TaskStatus.RanToCompletion)
    {
        ThrowForNonSuccess(task);
    }
}

This is my conclusion:

As can be seen GetResult() is calling TaskAwaiter.ValidateEnd(...), therefore Task.Result is not same GetAwaiter.GetResult().

I think GetAwaiter().GetResult() is a better choice instead of .Result because the latter doesn't wrap exceptions.

I read this at page 582 in C# 7 in a Nutshell (Joseph Albahari & Ben Albahari).

If an antecedent task faults, the exception is re-thrown when the continuation code calls awaiter.GetResult() . Rather than calling GetResult , we could simply access the Result property of the antecedent. The benefit of calling GetResult is that if the antecedent faults, the exception is thrown directly without being wrapped in AggregateException , allowing for simpler and cleaner catch blocks.

Source: C# 7 in a Nutshell's page 582

2

If a task faults, the exception is re-thrown when the continuation code calls awaiter.GetResult(). Rather than calling GetResult, we could simply access the Result property of the task. The benefit of calling GetResult is that if the task faults, the exception is thrown directly without being wrapped in AggregateException, allowing for simpler and cleaner catch blocks.

For nongeneric tasks, GetResult() has a void return value. Its useful function is then solely to rethrow exceptions.

source : c# 7.0 in a Nutshell

Not the answer you're looking for? Browse other questions tagged or ask your own question.