I have created a Windows Form - Form1, for understanding async-await in C#, and it has only two controls: a button (btnDemo
) and a label (lblRandom
). I am using .NET Framework 4.0.
This is the code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void btnDemo_Click(object sender, EventArgs e)
{
Task<int> myTask = new Task<int>(GetNumber);
myTask.Start();
lblRandom.Text = "Getting...";
lblRandom.Text = await myTask;
}
private int GetNumber()
{
Thread.Sleep(10000);
return new Random().Next(1, 100);
}
}
When I am trying to run this code, it shows me following error (on await myTask
line):
'
Task<int>
' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Task<int>
' could be found (are you missing a using directive or an assembly reference?)
Can someone please help me understand this error and provide a solution for the above code?