I recommend you read my async post post ; he explains how the async and await keywords work. Then, if you are interested in writing asynchronous code, go to my async article.
Relevant parts of the opening post:
The start of the asynchronous method is done exactly like any other method. That is, it works synchronously until it reaches “wait” (or throws an exception).
This is why the internal method in your console code example (without await ) was executed synchronously.
Waiting verifies that it expects that it is already completed; if the expected is already completed, the method simply continues to work (synchronously, like a regular method).
This is why the external method in your console code example (which was await internal method that was synchronous) was executed synchronously.
Later, when the wait is complete, it will execute the remainder of the asynchronous method. If you expect a built-in wait (for example, a task), then the remainder of the async method will execute in a "context" that was captured before the "wait" returns.
This "context" is SynchronizationContext.Current , if it is not null , in which case it is TaskScheduler.Current . Or a simpler version:
What is this "context"? Simple answer:
- If you are using a UI thread, then this is the UI context.
- If you are responding to an ASP.NET request, then this is the ASP.NET request context.
- Otherwise, this is usually the context of the thread pool.
Putting it all together, you can visualize async / await as follows: a method is split into several “pieces”, with each await acting as the point where the method is split. The first block always starts synchronously, and at each split point it can continue either synchronously or asynchronously. If it continues asynchronously, it will continue in the captured context (by default). UI threads provide the context that the next fragment in the UI thread will execute.
So, to answer this question, a special topic about user interface threads is that they provide a SynchronizationContext , that queues return to the same user interface thread.
I think no one wants anyone here in this forum to continue the discussion on how they appear in the comments, for example, so it’s better to ask a new question.
Well, Qaru is not intended for forums; this is a question and answer site. So this is not the place to ask for comprehensive study guides; this is the place where you are stuck trying to get the code to work, or if you don’t understand anything, having studied everything you can. This is why comments on SO (purposefully) are limited - they should be short, beautiful code formatting, etc. The comments on this site are for clarification, and not as a discussion or forum.