简体   繁体   English

System.Windows.Forms.Timer和MessageBox

[英]System.Windows.Forms.Timer And MessageBox

can someone please let me know why the System.Windows.Forms.Timer continues to show multiple message boxes? 有人可以让我知道为什么System.Windows.Forms.Timer继续显示多个消息框吗? I thought that it is on GUI thread ... and therefore after the first messagebox the GUI thread should block. 我以为它在GUI线程上...因此,在第一个消息框之后,GUI线程应该被阻止。 But this is not the case 但这种情况并非如此

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();


    }

    int nValue = 0;

    void tmr_Tick(object sender, EventArgs e)
    {
        nValue++;
        MessageBox.Show(nValue.ToString());
    }

    System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer();

    private void btnStartTimer_Click(object sender, EventArgs e)
    {            
        tmr.Interval = 500;
        tmr.Enabled = true;
        tmr.Tick += new EventHandler(tmr_Tick);
    }
}

The MessageBox.Show() method includes (as all modal dialogs do) a message loop that continues to pump window messages. MessageBox.Show()方法包括(就像所有模式对话框一样)一个消息循环,该循环继续泵送窗口消息。

Window messages are what allow a window to interact with the user (update itself, accept input, etc.), as well as what allows the Forms.Timer class to work. 窗口消息是允许窗口与用户进行交互(更新自身,接受输入等)的Forms.Timer ,也是使Forms.Timer类起作用的条件。

If you want your Forms.Timer to stop ticking when the dialog is shown, you need to set the timer's Enabled property to false before you show the dialog. 如果希望Forms.Timer在显示对话框时停止滴答,则需要在显示对话框之前将计时器的Enabled属性设置为false

In your Tick event stop the timer and then start again after MessageBox.Show like: 在您的Tick事件中,停止计时器,然后在MessageBox.Show之后再次启动。

void tmr_Tick(object sender, EventArgs e)
{
    tmr.Enabled = false;
    nValue++;
    MessageBox.Show(nValue.ToString());
    tmr.Enabled = true; 
}

The reason you are getting repeated MessgeBoxes is because your timer is continuing after showing the first MessageBox. 之所以会重复出现MessgeBoxes,是因为您的计时器在显示第一个MessageBox之后仍在继续。

A message box does not block the GUI-Thread. 一个消息框不会阻止GUI线程。 It's as simple as that. 就这么简单。 You can interact with the message box, after all :) 毕竟,您可以与消息框进行交互:)

Also: The internal workings of the timer are not clear, but I would guess that it runs on another thread and just returns on the GUI-Thread. 另外:计时器的内部工作方式尚不清楚,但是我猜想它会在另一个线程上运行,只是在GUI线程上返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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