14

In a WPF 4.5 application, I don't understand why the UI is blocked when I used await + a task :

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        // Task.Delay works great
        //await Task.Delay(5000);

        double value = await JobAsync(25.0);

        MessageBox.Show("finished : " + value.ToString());
    }

    private async Task<double> JobAsync(double value)
    {
        for (int i = 0; i < 30000000; i++)
            value += Math.Log(Math.Sqrt(Math.Pow(value, 0.75)));

        return value;
    }

The await Task.Delay works great, but the await JobAsync blocks the UI. Why ? Thank you.

Nico
  • 575
  • 3
  • 8
  • 19

2 Answers2

26

You should be getting a warning about JobAsync - it contains no await expressions. All your work is still being done on the UI thread. There's really nothing asynchronous about the method.

Marking a method as async doesn't make it run on a different thread - it's more that it makes it easier to join together asynchronous operations, and come back to the appropriate context.

I suspect it would be a good idea to take a step back and absorb some of the materials about async on MSDN... this is a good starting point...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
10

Try this:

private Task<double> JobAsync(double value)
{
    return Task.Factory.StartNew(() =>
    {
        for (int i = 0; i < 30000000; i++)
            value += Math.Log(Math.Sqrt(Math.Pow(value, 0.75)));

        return value;
    });
}
L.B
  • 114,136
  • 19
  • 178
  • 224
  • 2
    Rather than starting the task inside of the method it might make more sense to add a `Task.Run` call on the line with `await`, although the end result (if the function is never re-used) is identical. – Servy Oct 08 '12 at 17:55
  • 3
    Im in a similar scenario, still blocks the UI Thread. Are there any obvious gotchas? – IbrarMumtaz Apr 09 '14 at 22:22