What I'm asking is, where is GetJsonAsync executing when it's called from Button1_Click if this call doesn't create a new thread for it to execute on. Before the await within GetJsonAsync, isn't it executing the Console.WriteLine(...) within the UI context still?
I recommend reading my async
intro. In summary:
Every asynchronous method begins executing synchronously. This code:
public void Button1_Click(...)
{
var jsonTask = GetJsonAsync(...);
textBox1.Text = jsonTask.Result;
}
calls GetJsonAsync
on the UI thread, and it does begin executing on the UI thread. It executes Console.WriteLine
on the UI thread, new
s up a client on the UI thread, and even calls GetStringAsync
on the UI thread. It gets a task back from that method, and then await
s it (I'm ignoring the ConfigureAwait(true)
for simplicity).
The await
is the point at which things may become asynchronous. The task isn't complete (i.e., the client hasn't received the string yet), so GetJsonAsync
returns an incomplete task to its caller. Then Button1_Click
blocks the UI thread, waiting for that task to complete (by calling .Result
).
So, the state is currently GetJsonAsync
is no longer running on the UI thread. It is not actually "running" anywhere.
Later, when that string result arrives, the task that was returned from GetStringAsync
is completed, and GetJsonAsync
needs to resume executing. It's not already on the UI thread; it's not anywhere at the moment. Since the await
captured a UI context, it will attempt to resume on that context (on the UI thread).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…