Monday 16 May 2016

How to do async calls without locking the UI thread in WPF

WPF developers that have worked with async await have most likely run into problems with avoiding race conditions with the UI thread, either making the entire UI lock up or burden the UI thread and cause clients not responding. This article will show you how to avoid this. The way to do this is to await using another thread and afterwards use that result back again on the WPF thread to do the updates in the UI. We use ThreadPool.QueueUserWorkItem for this. As you can see, we user an inner method marked with async keyword to await the results. This is done to avoid the classic "async proliferation" seen in async code, where the async keyword spreads upwards to all methods. We instead use an outher method and call the async method and use the Result of the Task returned. We could do some quality checking here, to check if the Task succeeded of course. The Task object contains status information about if the results are really available or not and Result will throw an exception if there was an error in the retrieval of the async results from the lower layers of the software app layers. Example code:

DispatcherUtil.AsyncWorkAndUiThreadUpdate(Dispatcher.CurrentDispatcher, () => GetSomeItems(someId),
 x => GetSomeItemsUpdateUIAfterwards(x), displayWaitCursor:true);
//Note here that we retrieve the data not on the UI thread, but on a dedicated thread and after retrieved the
//result, we do an update in the GUI. 
private List<SomeItemDataContract> GetSomeItems(int someId)
        {
         var retrieveTask = GomeSomeItemsInnerAsync(someId);
         return retrieveTask.Result;
        }
 
private async Task<List<SomeItemDataContract>> GetSomeItemsInnerAsync(int someId)
        {
         List<SomeItemDataContract> retrieveTask = await SomeServiceAgent.GetSomeItems(someId);
         return retrieveTask;
        }

private void GetSomeItemsUpdateUIAfterwards(SomeItemDataContract x){
 if (x != null){
  //Do some UI stuff - remember RaisePropertyChanged
 }
}


Utility method:

public static void AsyncWorkAndUiThreadUpdate<T>(Dispatcher currentDispatcher, Func<T> threadWork, Action<T> guiUpdate, 
bool displayWaitCursor = false)
        {
         if (displayWaitCursor)
          PublishMouseCursorEvent<T>(Cursors.Wait);

         // ReSharper disable once UnusedAnonymousMethodSignature 
         ThreadPool.QueueUserWorkItem(delegate(object state)
            {
              T resultAfterThreadWork = threadWork();
              // ReSharper disable once UnusedAnonymousMethodSignature
              currentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action<T>(delegate {
       
              if (displayWaitCursor)
               PublishMouseCursorEvent<T>(Cursors.Arrow);
 
              guiUpdate(resultAfterThreadWork);
           }), resultAfterThreadWork);

            });
 
        }

The PublishMouseCursorEvent publishes a prism event that is captured by a Bootstrapper class, but what you choose to do here is of course up to you. One way is to subscribe such an event (either a CompositePresentationEvent as in Prism or an ordinary CLR event for example):
private void OnCursorEvent(CursorEventArg eventArg)
{
 if (eventArg != null)
 {
 Mouse.OverrideCursor = eventArg.Cursor;
 }
}


Share this article on LinkedIn.

37 comments:

  1. Did you know that that you can make dollars by locking selected areas of your blog / website?
    Simply join Mgcash and run their Content Locking plug-in.

    ReplyDelete
  2. Does your ex not return your 800 Do you really want to hear your ex's voice again? Do you miss your ex like crazy, and want to get your ex back? Well, you have hit the jackpot then! You are about to see 3 proven methods that will get your ex to return your phone calls. Here is how you can pull your ex back once and for all...

    ReplyDelete
  3. There are so many android apps development companies that offer excellent services to the clients. Let us learn more about the android applications. have a peek here

    ReplyDelete
  4. Many online colleges are offering degree distinctions in information technology. These accredited programs are preparing students to enter the work force and become active, successful members of the industry. mobile tracker free

    ReplyDelete
  5. Many online colleges are offering degree distinctions in information technology. These accredited programs are preparing students to enter the work force and become active, successful members of the industry. phone app to spy camera

    ReplyDelete
  6. This web site is usually a walk-through its the data you wished concerning this and didn’t know who ought to. Glimpse here, and you’ll definitely discover it. [url=https://www.totolove24.com]토토사이트[/url]

    ReplyDelete
  7. Aw, this was a really nice post. In idea I want to put in writing like this moreover – taking time and actual effort to make a very good article… however what can I say… I procrastinate alot and not at all seem to get one thing done. iphone emulator for pc

    ReplyDelete
  8. In fact, the best thing about this film is how excellent it is as an epic quest film instead of how hilarious it is. wireless

    ReplyDelete
  9. Thank you a lot for sharing this with all of us you actually understand what you’re talking approximately! Bookmarked. Please also visit my site =). We may have a hyperlink alternate contract among us! euregion

    ReplyDelete
  10. Perhaps you should update the php server on your webhost, WordPress is kinda slow…”‘, chinese takeaway food in Camberley

    ReplyDelete
  11. What is a DVR hidden spy camera? It is a new breed of spy camera with a DVR built in. See what they can do for you. diy spy camera wireless

    ReplyDelete
  12. Hello! I recently would want to provide a enormous thumbs up for that excellent information you’ve got here about this post. I’ll be coming back to your website to get more soon. bet188

    ReplyDelete
  13. Deference to website author , some great entropy. buy steroids

    ReplyDelete
  14. Perhaps you should update the php server on your webhost, WordPress is kinda slow…”‘, 꽁머니 공유

    ReplyDelete
  15. The number of users accessing websites and web applications on their mobile devices has been increasing steadily. Likewise, popular search engines like Google also use mobile friendliness as a key metric to rank websites. Hence, enterprises nowadays focus on enhancing the mobile user experience of their websites. They even require developers to build mobile websites that keep visitors engaged and convert them into customers. The developers can make a website mobile-friendly in a number of ways. They can further accelerate mobile website development by implementing several techniques and best practices. However, it is also important for developers to avoid a number of mistakes to make the website deliver optimal mobile user experience. originally us

    ReplyDelete
  16. I really like what you guys are up too. This sort of clever work and coverage! Keep up the very good works guys I’ve included you guys to my own blogroll. boomerang link's awakening switch

    ReplyDelete
  17. Hello! I would wish to provide a enormous thumbs up for the great info you could have here about this post. We are coming back to your blog for further soon. teleport to an encounter

    ReplyDelete
  18. Found this on MSN and I’m happy I did. Well written article. 마사지

    ReplyDelete
  19. Hey there! Good post! Please when all could see a follow up! 스웨디시

    ReplyDelete
  20. Incredibly best man toasts, nicely toasts. is directed building your own by way of the wedding celebration as a result are supposed to try to be witty, amusing and consequently unusual as well as. best mans speech 셔츠룸

    ReplyDelete
  21. I don’t have time right now to write a lot, but when I returned tomorrow evening, I will explain in depth why I disagree with this article. educationspike

    ReplyDelete
  22. Wow! Thank you! I continually needed to write on my website something like that. Can I include a fragment of your post to my website? cyber techyt

    ReplyDelete
  23. My brother recommended I might like this website. He was entirely right. This post truly made my day. You cann’t imagine just how much time I had spent for this info! Thanks! 강남가라오케

    ReplyDelete
  24. Thank you for sharing superb informations. Your site is very cool. I’m impressed by the details that you have on this website. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for extra articles. You, my friend, ROCK! I found just the info I already searched everywhere and just couldn’t come across. What a great web site. unique auto mag

    ReplyDelete
  25. Wow, wonderful blog layout! How long have you ever been blogging for? you made running a blog glance easy. The full look of your website is great, let alone the content! https://rgray.io/services/crypto-pr/

    ReplyDelete
  26. The Advantages Of Playing Slots Online. Slots have always been a source of entertainment for anyone that’s played them. Advantages of playing slots online

    ReplyDelete
  27. This web site is usually a walk-through its the data you wished concerning this and didn’t know who ought to. Glimpse here, and you’ll definitely discover it. Swing Chair

    ReplyDelete
  28. There are so many android apps development companies that offer excellent services to the clients. Let us learn more about the android applications. capricorn man stopped texting

    ReplyDelete
  29. We still cannot quite feel like I could truthfully come to be a type checking important points available your webblog. Our neighbors and i are sincerely thankful for your personal generosity nicely giving me possibility pursue our chosen profession path. Just info I bought within your web-site. apply from EasyFinance i need $400 dollars now bad credit

    ReplyDelete
  30. I just put the link of your blog on my Facebook Wall. very nice blog indeed.,’-”, $700 loan UnitedFinances safe apply

    ReplyDelete
  31. I’m impressed, I have to admit. Really rarely can i encounter a blog that’s both educative and entertaining, and without a doubt, you’ve hit the nail to the head. Your idea is outstanding; the problem is something which inadequate persons are speaking intelligently about. My business is very happy i found this in my look for some thing in regards to this. cub net login

    ReplyDelete


  32. where you can buy citizenship and a second passport. buy eu passport


    ReplyDelete
  33. Thanks for the reponse. I’ll put this information to good use. https://saratogapartnership.org/

    ReplyDelete
  34. Our mothers are our superheroes and greatest allies, yet we often don't tell them enough about the amount they're worth. A mother is she who can replace all others however whose place no other person can take. Let's celebrate this new year with your mother and send her some beautiful warm wishes. Here you'll find so many beautiful new year wishes for mother.

    ReplyDelete