asynchronous - Example of an Async Method that uses the main thread without blocking it.c# -
in page 18 concurrency in c# cookbook,stephen cleary define asynchronous programming : "a form of concurrency uses futures or callbacks avoid unnecessary threads." in code async method uses multi threads (thread pool). can same 1 please show me example of async method uses main thread without blocking it.
consider, example, method sends http request , gives http response. if method synchronous (e.g. webrequest.getresponse()
) 90% time method wait due network latency, , hence thread on method executed sleep , nothing.
when using async method (e.g. httpclient.postasync()
) , await result, calling method ends first await
, calling thread free process other work or can returned threadpool. when http response received, work resumed.
the thread on continuation run depends on synchronizationcontext
. so, if ran , awaited async method ui thread, continuation run on ui thread. if ran , awaited async method background thread continuation run on threadpool thread.
async void button_click(object sender, eventargs args) { _button.enabled = false; // invoked on main thread var response = await _httpclient.postasync(request); // not block main thread , ui responsive // won't occupy threadpool thread time response processresponse(response); // invoked on main thread }
some async methods run in background , occupy background thread time needed completed, , (io basically) not.
Comments
Post a Comment