5

I want unblock the ui using threads.

Could you tell me what is the difference between this code:

private async void button1_Click(object sender, EventArgs e)
{
    int result = await Calculate(1, 2);

    label1.Text = result.ToString();
}

private async Task<int> Calculate(int number1, int number2)
{
    return await Task.Run(() =>
    {
        Thread.Sleep(5000);
        return number1 + number2;
    });
}

And this code:

private async void button1_Click(object sender, EventArgs e)
{
    int result = await Calculate(1, 2);

    label1.Text = result.ToString();
}

private async Task<int> Calculate(int number1, int number2)
{
    await Task.Delay(5000);
    return number1 + number2;
}
michael
  • 647
  • 2
  • 7
  • 17

1 Answers1

2

The main difference is that Task.Run creates a new thread (refer to this MSDN documentation's Threads section).
So the new thread created blocks for 5 seconds in the first case and then returns the result (Meanwhile, the main thread is available for use, so await returns back the control to the caller from Task.Run(...) )

In the second case too, after the await, control is transferred to the caller and the Task.Delay is going on in the main thread. No new thread is created.

So as you mentioned in the question, if you want to go for multi-threading, using Task.Run() along with async and await will give you a multitude of possibilities.

For more details on async and await control flow, refer the above mentioned documentation. Its a very helpful and detailed MSDN read!

Vandesh
  • 6,368
  • 1
  • 26
  • 38