Expectation and expression

I am following the wait for the MSDN tutorial, and I am trying to figure out the difference between using awaitas instead of using awaitas an expression. All this asynchronous expected thing bends my mind, and I can not find examples for this particular case.

Basically, I wanted to see how to use multiple asynchronously await, which means that I don't want to wait for the first to complete before the second starts. This, for me, hits the goal of asynchrony:

private async void button1_Click(object sender, EventArgs e)
{
    // Using await as an expression
    string result_a = await WaitAsynchronouslyAsync();
    string result_b = await WaitAsynchronouslyAsync();

    // This takes six seconds to appear
    textBox1.Text = result_a + Environment.NewLine;
    textBox1.Text += result_b;
}

public async Task<string> WaitAsynchronouslyAsync()
{
    await Task.Delay(3000);
    return "Finished";
}

However, with a subtle change, it takes only 3 seconds to display two "Ready", what I want - two awaitwork really asynchronously:

private async void button1_Click(object sender, EventArgs e)
{
    var a = WaitAsynchronouslyAsync();
    var b = WaitAsynchronouslyAsync();

    // Using await as a statement
    await a;
    await b;

    // This takes three seconds to appear
    textBox1.Text = a.Result + Environment.NewLine;
    textBox1.Text += b.Result;
}

My question is: why do they behave differently? What thin point do I not see here?

+5
2

-, parallelism . ( , ), ..

- - await - . , , , , , . , , :

// Still takes 6 seconds...
var a = WaitAsynchronouslyAsync();
await a;

var b = WaitAsynchronouslyAsync();
await b;

6 . , , . .

, awaitables:

// This will only take 3 seconds
var a = WaitAsynchronouslyAsync();
var b = WaitAsynchronouslyAsync();
string result_a = await a;
string result_b = await b;

, , / - , /// ///.

+11

await . , , , 1 , 2 .

,

string result_a = await WaitAsynchronouslyAsync(); 
string result_b = await WaitAsynchronouslyAsync(); 

:

  • (a)
  • a ( )
  • a 3 , ; (b)
  • ( )
  • b 3 ,

:

var a = WaitAsynchronouslyAsync();     
var b = WaitAsynchronouslyAsync();     
await a;     
await b;     
  • (a)
  • (b) .
  • (a) "" (.. )
  • () 3 , ()
  • b 3 , (a)
+4

All Articles