I am learning the basics of async
and await
, and sometimes it's not clear whether I should build a method as async
or not.
To make the question clear, I wrote two ways below to do the same thing. In both samples below, MyMethod()
is called by button1's click event and does (presumably) the same thing:
First way:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int MyMethod()
{
int x = 0;
do
{
Thread.Sleep(100);
x++;
} while (x < 10);
return x;
}
private async void button1_Click(object sender, EventArgs e)
{
Task<int> task = new Task<int>(MyMethod);
task.Start();
int MyNumber = await task;
label1.Text = MyNumber.ToString();
}
}
Second way:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async Task<int> MyMethodAsync()
{
int x = 0;
do
{
await Task.Delay(100);
x++;
} while (x < 10);
return x;
}
private async void button1_Click(object sender, EventArgs e)
{
int MyNumber = await MyMethodAsync();
label1.Text = MyNumber.ToString();
}
}
My confusion is, how do I choose between these two methods? Is there is a recommended way?
As a beginner, my tendency is to convert MyMethod()
to a Task
only if we need asynchronous tasks inside MyMethod()
. But I cannot make a conclusion whether it is fine to implement MyMethod()
as a Task in others cases, too.
If the first way works for us, is second way (converting MyMethod to a Task) redundant or could it even have bad consequences?