C#Windows窗体-每次我运行代码时,消息框都会再次显示

时间:2019-06-11 18:15:22

标签: c# message messagebox box

我有一个Windows Forms应用程序,用于测试排序算法,它由一个表单组成。测试完成后,该表单会显示一个消息框,说明测试已完成,但是第一次测试后它会显示一次,第二次之后它会显示两次,第3次之后的3次,依此类推。 后台工作人员从“ RunWorkerCompleted”方法调用显示MessageBox的方法。

private void RunAlgorithmTests()
//this is called from an onclick method
{
    backgroundWorker.DoWork += (s, e) =>
    {
        test.RunTests();
    };

    backgroundWorker.RunWorkerCompleted += (s, e) =>
    {
        ShowCompleteMessage();
    };
    backgroundWorker.RunWorkerAsync();
}


private void ShowCompleteMessage()
//show this message on successful test complete
{
    string title = "Test završen!";
    string message = "Test završen nakon" + swatch.Elapsed.Hours.ToString() + ":" + swatch.Elapsed.Minutes.ToString() + ":" + swatch.Elapsed.Seconds.ToString();
    this.Text = "Aplikacija za testiranje algoritama sortiranja";
    if (test.complete)
    {
        MessageBox.Show(message, title);
    }
}

MessageBox只能在每次测试结束时出现一次,但每次测试运行都会增加它出现的次数。

2 个答案:

答案 0 :(得分:0)

根据建议,仅一次收录这些事件。这是通过Form的Load()事件完成的:

    private void Form1_Load(object sender, EventArgs e)
    {
        backgroundWorker.DoWork += (s, e) =>
        {
            test.RunTests();
        };

        backgroundWorker.RunWorkerCompleted += (s, e) =>
        {
            ShowCompleteMessage();
        };
    }

    private void button1_Click(object sender, EventArgs e)
    {
        RunAlgorithmTests();
    }

    //this is called from an onclick method
    private void RunAlgorithmTests()
    {
        backgroundWorker.RunWorkerAsync();        
    }

答案 1 :(得分:0)

问题在于,每次运行后台工作程序时,都会为这两个事件添加其他新的处理程序。第一次,您每个人都有一个处理程序。下次,您再添加一个,所以您有两个。两者都被称为。下次,您添加另一个,这三个都将被调用。

您要做的是确保仅发生一次。

我喜欢您将事件处理程序初始化放入其自己的方法中的想法,因此我们会坚持下去。

//  Your Form class is probably called something else. 
public Form1()
{
    InitializeComponent();

    //  Since backgroundWorker was created in the form designer, it will have been 
    //  initialized in InitializeComponent(). Therefore, this has to happen after 
    //  InitializeComponent() is called. 
    InitializeBackgroundWorkerHandlers();
}

private void InitializeBackgroundWorkerHandlers()
{
    backgroundWorker.DoWork += (s, e) =>
    {
        test.RunTests();
    };

    backgroundWorker.RunWorkerCompleted += (s, e) =>
    {
        ShowCompleteMessage();
    };
}

//  this is called from an onclick method
private void RunAlgorithmTests()
{
    backgroundWorker.RunWorkerAsync();
}