locked
Why does an async method hang UI contra using Task.Run()..? RRS feed

  • Question

  • I have run a simple test example below which reflects a realistic scenario in my real app. It just includes two Buttons and two TextBlocks. 

    Questions:

    • Why does Example#1 using await DoWork() hang the whole UI until the work has been done..? I thought the whole idea with async methods was an easy and quick way to get responsive UI?
    • Example #2 using await Task.Run(()=>DoWork2() does update UI nicely, however, acts on a separate thread and there is a need to use the Dispather to update UI and other objects. Any drawbacks here other than this..?
    • At compile time, there is always a warning on the SimulateWork() method saying "..method lacks await operators and will run synchonously, consider using await operarotr etc.." WELL for sure this method is synchron! That is why it is wrapped in async method/thread in the first place. Is there any way I can get rid of these warnings, I am afriad I have quite a few of them in my real app.

    Thanks for any comments.

            // Example #1
            private async void Button_Click1(object sender, RoutedEventArgs e)
            {
                myLabel1.Text = string.Empty;
                await DoWork1();
            }
            private async Task DoWork1()
            {
                for (int i = 0; i < 100; i++)
                {
                    myLabel1.Text = i.ToString();
                    await SimulateWork();
                }
            }
    
            // Example #2
            private async void Button_Click2(object sender, RoutedEventArgs e)
            {
                myLabel2.Text = string.Empty;
                await Task.Run(() => DoWork2());
            }
            private async void DoWork2()
            {
                for (int i = 0; i < 100; i++)
                {
                    // Use Dispather here in order to update UI from another thread
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                                  {
                                      myLabel2.Text = i.ToString();
                                  });
                    await SimulateWork();
                }
            }
    
            // Simulate some synchron work being done in 20 ms
            private async Task SimulateWork()
            {
                SpinWait.SpinUntil(() => false, 20);
            }


    • Edited by Southbranch Wednesday, January 15, 2014 6:27 PM
    Wednesday, January 15, 2014 6:26 PM

All replies