Having the Code Below in Windows forms.
private bool test = false;
private async void button1_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
test = !test ;
textBox2.Text = test.ToString(); // Each time i click text box switches to true and false
for (int i = 0; i < 1000000; i++)
{
textBox1.Text = i.ToString();
}
});
textBox2.Text = "Done"; // This will never happen until the task is done
}
If i Click button the textbox text Changes from 0 to 1000000.
Since i use async/await. the form will not freeze and I can see the Textbox Counting from 0 to 1000000.
But the problem is if i click the button again another thread spawn and textbox value changes by two threads. and you can see two counters from two threads changing textbox value.
if you click again you get 3 threads, 4 threads etc....Also textbox2 changes to true, false, true ....
This was just a test for me to see how actually async await works.
But i think im using it wrong. im afraid if i use async in my projects and end up to this situation.
How can i stop Threads spawning from single async method.
Currently I think each time i press the button New async Method spawns.
Here is What i see.
