2

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.

enter image description here

0

2 Answers 2

1

There's some confusion in the comments about what's happening. Especially since the posted code shouldn't actually work (it's not thread-safe).

The simplest way to reproduce this (drop a Button and a Label on a Form):

private async void button1_Click(object sender, EventArgs e)   // add the async
{
    for (int i = 0; i < 1000; i++)
    {
        label1.Text = "" + i;
        await Task.Delay(100);
    }
}

You can make this run multiple loops at once, you can increase the Delay to see that better. Note that there are no extra Threads involved, it all runs on the main GUI thread.

The keys here are async and await, they make the compiler turn a call to this method into a state machine and that way it can interleave the execution of multiple loops at once. Think of it as a method that can be paused at the await call and be resumed later. All on the same thread.

More importantly, it interleaves the loop(s) with the main thread so that that can continue to handle input messages and update the screen.

That was the 'why' part.

The how to solve it part depends on what you actually want, the now deleted answer from @CSharpie shows the basic pattern: use a boolean field as a guard, or disable & enable the Button.

5
  • Thank you very much. i didnt know i can run method like this. async is completely different from what i thought. and from Task.Run. Jul 1, 2015 at 6:55
  • 1
    Use the async void pattern only for event handlers. Everywhere else, use async Task.
    – H H
    Jul 1, 2015 at 15:57
  • This is completely different code. I already knew this was possible, but you're running the assignment on the UI thread, and there is no Task.Run. In the OP's code, either the entire lambda is running on separate threads (in which case they should be getting an error), or it isn't (in which case they shouldn't be seeing the competing threads). What I was interested in was how OP's code was causing the behavior they're describing. Jul 1, 2015 at 17:51
  • 1
    @Asad - You picked up on a different question along the way. You can run the original code outside the debugger (Ctrl+F5). It isn't thread-safe but when you disable the checks that way nothing terrible happens. This answer shows the thread-safe (thread-free) version exhibiting the same core issue.
    – H H
    Jul 1, 2015 at 18:03
  • Ah, ok, that makes much more sense. I didn't realize this exception only happens when you're in debug mode. Jul 1, 2015 at 18:18
0

Disable the button after pressed and and enable it when it finishes.

1
  • its better to say. the best way is. Because what i did was wrong style of coding. thats what async method does. UI should be updated by the final results not by multitasking. Jun 30, 2015 at 22:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.