Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

c# - What is the difference between .Wait() vs .GetAwaiter().GetResult()?

My method returns Task. I want to wait until it finished. What should I use .Wait() or .GetAwaiter().GetResult()? What is the difference between them?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Both are a synchronous wait for the result of the operation (and you should avoid those if possible).

The difference is mainly in handling exceptions. With Wait, the exception stack trace is unaltered and represents the actual stack at the time of the exception, so if you have a piece of code that runs on a thread-pool thread, you'd have a stack like

ThreadPoolThread.RunTask
YourCode.SomeWork

On the other hand, .GetAwaiter().GetResult() will rework the stack trace to take all the asynchronous context into account, ignoring that some parts of the code execute on the UI thread, and some on a ThreadPool thread, and some are simply asynchronous I/O. So your stack trace will reflect a synchronous-like step through your code:

TheSyncMethodThatWaitsForTheAsyncMethod
YourCode.SomeAsyncMethod
SomeAsync
YourCode.SomeWork

This tends to make exception stack traces a lot more useful, to say the least. You can see where YourCode.SomeWork was called in the context of your application, rather than "the physical way it was run".

An example of how this works is in the reference source (non-contractual, of course).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...