ChatGPT解决这个技术问题 Extra ChatGPT

Is Task.Result the same as .GetAwaiter.GetResult()?

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;
From the docs of GetResult: "This type and its members are intended for use by the compiler." Other person shouldn't be using it.
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)
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.

I
It'sNotALie.

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.


@JayBazuzi Not if your unit testing framework supports async unit tests, which I think newest versions of most frameworks do.
@JayBazuzi: MSTest, xUnit, and NUnit all support async Task unit tests, and have for some time now.
pushing back on the 100x - it's 1000x worse to use await if you're adapting old code and using await requires a rewrite.
@AlexZhukovskiy: I disagree.
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.
I
Ian Kemp

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


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: 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.
Can't you avoid deadlocks in this scenario with (Task).ConfigureAwait(false).GetAwaiter().GetResult(); ?
@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
I don't get it. Task.Wait and Task.Result are broken by design? Why aren't they made obsolete?
L
Liam

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."


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.
So we shouldn't use it?
If two tasks end with an exception you will loose the second one in this scenario Task.WhenAll(task1, task2).GetAwaiter().GetResult();.
N
Nuri Tasdemir

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.


This is not true. Check out my fiddle which uses exactly this construct: dotnetfiddle.net/B4ewH8
@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.
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.
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.
O
Ogglas

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


If you vote down, please say why. Hard to improve answers otherwise.
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 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/…
I
Ian Kemp

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


A
Ali Abdollahi

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