I have a program that checks what is the user reaction time based on speed he clicks on the button when it changes to green. I would like the function that is working after clicking the button to run in the background.
I though by using Task it will make it asynchronously but it seems to not be the case. I understand that there is an await and probably I should make it somehow return to place it was called but I have a problem finding the solution.
My code so far looks like this
public partial class Reaction : Form
{
Stopwatch timer;
bool start = false;
public Reaction()
{
InitializeComponent();
button1.Text = "START";
button1.BackColor = Color.Red;
}
public async Task Test()
{
if (start)
{
timer.Stop();
TimeSpan timespan = timer.Elapsed;
string timeString = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10);
MessageBox.Show(timeString);
button1.BackColor = Color.Red;
button1.Text = "START";
start = false;
}
else
{
Random rnd = new Random();
int number = rnd.Next(1, 10000);
System.Threading.Thread.Sleep(3000 + number);
timer = Stopwatch.StartNew();
button1.BackColor = Color.Green;
button1.Text = "CLICK";
start = true;
}
}
private async void button1_Click(object sender, EventArgs e)
{
button1.BackColor = Color.Red;
button1.Text = "Dont click";
await Test();
}
}