winforms - VB.NET: What happens if I run CPU-bound code using Await? -
i trying understand async/await. understand should not await cpu-bound method, understanding curious happens if do. consider:
public async function dosometasks() await longrunningcpuboundmethod1() longrunningcpuboundmethod2() end function public async function longrunningcpuboundmethod1() task ' stuff synchronously end function public sub longrunningcpuboundmethod2() ' stuff synchronously end sub
how task scheduler handle cpu resources? in order these methods execute? longrunningcpuboundmethod1 or longrunningcpuboundmethod2 execute first?
the thing remember here async
/await
code not multi-threaded. can use them multi-threaded code awaiting items start separate thread, allow break several tasks efficiently in same thread.
this doesn't come without overhead; switching between asynchronous tasks has cost. when await cpu-bound tasks, you've added cost cpu-intensive work, , therefore made things worse rather better. however, if combine code starts cpu-heavy tasks in separate thread, , uses waithandle or task send results back, might fine again (depending on how many items you're awaiting relative number of available cores), because you're taking advantage of multiple cores in cpu.
additionally, let's @ in context of .net winforms. it's important remember here never want significant cpu work on main ui thread. really, anything blocks more few milliseconds problematic. if thread busy, windows message pump doesn't run, can't respond events, , user interface becomes unresponsive.
to understand await
in context, think of if breaks method 2 parts (or more, if there more 1 await
). , including line await
runs immediately, , after await hidden away compiler in new callback method (called continuation) called same context (including variables local original method) , in same thread when await
has finished.
with information, should clear if directly await
cpu-bound method, you're still doing work on ui thread, , user interface still in trouble. however, can again account starting cpu-bound method in it's own thread. await
, in conjunction task
s, make relatively easy without having write lot of new code. it's better old doevents()
technique.
Comments
Post a Comment