How to implement Basic Async Await method
Here is the basic way to implement Async - await method on your own.
Here is an example (Winform project - .NET Framework)
bool started = false; //This is a flag telling if we have to display current Date and time
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if ( started)
this.Text = DateTime.Now.ToLongTimeString(); //Display it if started is true
}
private void Form1_Load(object sender, EventArgs e)
{
// Normal intialization, - start the timer.
LblName.Text = "";
this.Text = "Awaiting click the button";
timer1.Start();
}
//The async method itself, calling the Task.Delay with await prefix
private async Task<string> ReadTextAsync()
{
await Task.Delay(TimeSpan.FromMilliseconds(6000));
//Set the timer-flag to false when counting is done
started = false;
this.Text = "Awaiting click the button";
return "Time done....";
}
//Remember to set button click as async
private async void button1_Click(object sender, EventArgs e)
{
LblName.Text = "";
started = true;
string text = await ReadTextAsync();
LblName.Text = text;
}
// A bit different when handling a conventional Controller method in MVC, returning a View:
public async Task<IActionResult> Index()
{
//Do something here....
.
.
.
return await Task.Run(() => View()); //Return the View as usual.
}