igel1
igel1

Reputation: 242

C#: How to stop my program until a button is clicked

I start a program loop with a click on Button1. The loop is executed in the Click-Event-Handler of Button1.

My requirement:

The loop shall stop every time at a certain point in code and wait for Button2 to be pressed before execution goes on.

I tried:

private ManualResetEvent mre = new ManualResetEvent(false);

and in my Button1 Event-Handler:

mre.WaitOne();

and in my Button2 Event-Handler:

mre.Set();
mre.Reset();

...but when I reach WaitOne() in my Button1-Event-Handler all my application freezes. Do you have any hints for me, what I am doing wrong?

Upvotes: 0

Views: 1269

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39122

Mark your Button1 click handler with async (before the void in the return type), then await a Task that calls WaitOne():

private ManualResetEvent mre = new ManualResetEvent(false);

private async void button1_Click(object sender, EventArgs e)
{
    button1.Enabled = false;

    for(int i = 1; i <=100; i++)
    {
        label1.Text = i.ToString();
        await Task.Delay(100);

        if (i % 10 == 0)
        {
            label2.Text = "Press Button2 to Continue";
            await Task.Run(() => { 
                mre.WaitOne();
                mre.Reset();
            });
            label2.Text = "";
        }
    }

    button1.Enabled = true;
}

private void button2_Click(object sender, EventArgs e)
{
    mre.Set();
}

Note that you can have multiple awaits inside the handler. The first one obviously isn't necessary; it just slows down the loop so you can see the number changing. Also note that you could change the delay to a ridiculously long amount and the form would still remain responsive!

Upvotes: 2

Related Questions