I am trying to learn async await. I am trying a simple C# Windows Forms application with just 1 textbox and 1 button.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
const bool USE_GET_STRING_DIRECTLY = true; // just for switching logic on button1_click
private async void button1_Click(object sender, EventArgs e)
{
textBox1.Clear();
if (USE_GET_STRING_DIRECTLY)
{
// Code #1 <<<---------------------
textBox1.Text += await GetString();
}
else
{
// Code #2 <<<---------------------
var s = await GetString();
textBox1.Text += s;
}
}
async Task<string> GetString()
{
await Task.Delay(2000);
return "Test";
}
}
}
I am using USE_GET_STRING_DIRECTLY just as a sort of conditional compilation to switch between Code #1 and Code #2.
If USE_GET_STRING_DIRECTLY is true, Code #1 will be executed
textBox1.Text += await GetString();
I press the button twice within 500msec. I will see the text "Test" on the textbox.
Now, I set the USE_GET_STRING_DIRECTLY to false, Code #2 will be executed:
var s = await GetString();
textBox1.Text += s;
I press the button twice within 500msec. I will see the text "TestTest" on the textbox. It is printing the Test twice.
It seems to me that code #1 and #2 are the same but they are exhibiting different behavior. The difference is that other one is equated to a variable, while the other one is equated to a Textbox.Text. What could be the reason for this? I am pretty new to async/await so I am pretty sure I am missing something here.