按下按钮1时,等待按钮2被单击

时间:2015-09-17 16:32:28

标签: c# winforms button asynchronous async-await

我有一个button2,点击时有很多代码要执行。

在某些时候,我需要等到布尔值设置为true,并且当按下按钮1时,布尔值为true。 (当button2的代码正在运行时,我无法按下按钮1。)

我已经搜索过了,但我找到的只是运行异步的方法。我怎么能等待按下按钮1?

1 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案(可能不是最优雅的):

public partial class Form1 : Form
{
    // Variable to store whether button one has been clicked or not
    private bool btnOneClicked = false;

    // ..

    private void btnOne_Click(object sender, EventArgs e)
    {
        // When button one is clicked, execute the code that needs to run before waiting for your second button to be clicked
        LongCodeToExecuteFirst();
        // Set your variable to true to say that button one has been clicked
        btnOneClicked = true;
    }

    private void btnTwo_Click(object sender, EventArgs e)
    {
        // First check if button one has been clicked
        if (btnOneClicked)
        {
            // If it has, execute the rest of the code that needed to be executed after button two was pressed
            LongCodeToExecuteSecond();
            // Reset our button one pressed variable to false
            btnOneClicked = false;
        }
    }

    private void LongCodeToExecuteFirst()
    {
        // Code to execute before button two is pressed
    }

    private void LongCodeToExecuteSecond()
    {
        // Code to execute after button two is pressed
    }
}