I'm new to asynchronous programming, I always have difficulty in understanding UI thread lifecycle. Let's said we work on a webform, and in the page load method, we made an asynchronous call as:
private SynchronizationContext uiCtx;
...
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
...
WebRequest req = WebRequest.Create("http://www.google.com/#q=weather");
// Must make this call on the UI thread
uiCtx = SynchronizationContext.Current;
AsyncCallback callback = delegate(IAsyncResult iar)
{
WebResponse resp = req.EndGetResponse(iar);
ProcessResponse(resp);
};
req.BeginGetResponse(callback, null);
...
}
}
private void ProcessResponse(WebResponse resp)
{
// This code is on the threadpool thread
StreamReader reader = new StreamReader(resp.GetResponseStream());
SendOrPostCallback callback = delegate
{
// this runs on the UI thread
UpdateUI(reader.ReadToEnd());
// must Dispose reader here as this code runs async
reader.Dispose();
};
uiCtx.Post(callback, null);
}
I can get the idea that we want a work thread to get the job done and update UI, so we use SynchronizationContext
to move work back onto the UI thread.
I have the following questions:
Q1-Why the worker thread is not supposed to update UI directly, is any particular reasons for that?
Q2-We know that for asynchronous programming model, the worker threads in the thread pool are background threads. Let's assume the async call takes 3 seconds to get the result back, but the main thread will finish quickly after the page_load
, if UI thread has already finished, it cannot execute the job passed from the worker thread, can it? So how can we control the UI thread to let it not finishing quickly?
Q3-if the worker thread finishes first, now the job will be moved back to UI thread, let's suppose that UI thread is also executing something else, so does it mean that the UI thread will get its job done first then start to execute the work passed from the worker thread?