简体   繁体   中英

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM