If Async/ Await is not using a new thread, how can UI be responsive? RRS feed

  • Question

  • I have read that the async/await usage does not use a thread pool thread when being used(for eg WPF app), and if so, how is it that a UI is responsive when you are doing a long computing task using that? if not a Thread pool thread, wouldn't the UI thread have to do that job? And if so, how can UI be responsive ?

    Thanks in advance


    Monday, August 5, 2019 5:32 PM

All replies

  • It's a more complicated concept than first appears.  "await" does not actually block the thread.  Internally, it returns to the caller so processing can continue.  Later, when the event being awaited happens, control will resume after the "await" call.

    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Monday, August 5, 2019 5:39 PM
  • To me it sounds like the code after await is put in a "continueWith" of Task. But the question is, if not a separate worker thread, it must be the UI thread that is doing the long processing( one we are awaiting)? How can it do both? Do the long calculation and keep the UI responsive?  
    • Edited by Zest4Quest Monday, August 5, 2019 9:01 PM
    Monday, August 5, 2019 5:52 PM
  • Yes, if the "async" function is CPU bound, then the UI responsiveness will suffer.  "async" by itself is designed for tasks that block, like fetching a web resource or doing I/O.  If your "async" function is CPU-intensive, then it should do Task.Run, which will spawn a separate thread.

    The nice thing is that the "await" doesn't need to care.

    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Tuesday, August 6, 2019 4:01 AM
  • You are being distracted by async/await. Facilities for creating multiple threads existed prior to the introduction of async/await. Simply do not rely on async/await to create tasks. Use async/await to manage tasks when necessary.

    Sam Hobbs

    Tuesday, August 6, 2019 3:15 PM