在MessageBox.Show()暂停基于计时器的程序

时间:2011-08-25 02:58:06

标签: c# .net timer messagebox dialogresult

我有一个MessageBox.Show事件,我想在MessageBox保持打开状态时阻止基于计时器的方法运行。

这是我的代码(每隔x分钟更改网络上文件位置的值):

public void offlineSetTurn()
{
    try
    {
        using (StreamWriter sWriter = new StreamWriter("FileLocation"))
        {
            sWriter.WriteLine(Variable);
        }
    }
    catch (Exception ex)
    {
        DialogResult result = MessageBox.Show("Can't find file.  Click Okay to try again and Cancel to kill program",MessageBoxButtons.OKCancel);

        if (result == DialogResult.OK)
        {
            offlineSetTurn();
        }
        else if (result == DialogResult.Cancel)
        {
            Application.Exit();
        }
    }
}

我的表单中的方法每三十秒调用一次。这意味着每隔30秒就会弹出另一个MessageBox。有没有办法暂停使用MessageBox的应用程序,如果没有,什么是解决此问题的最佳方法?如果可能的话,我想避免使用Timer.Stop(),因为它会重置Timer计数。

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是设置一个标志,指示消息框当前是否已打开:

private bool isMessageBoxOpen = false;

public void offlineSetTurn()
{
    if (isMessageBoxOpen)
        return;

    try
    {
        using (StreamWriter sWriter = new StreamWriter("FileLocation"))
        {
            sWriter.WriteLine(Variable);
        }
    }
    catch (Exception ex)
    {
        isMessageBoxOpen = true;
        DialogResult result = MessageBox.Show("Can't find file.  Click Okay to try again and Cancel to kill program",MessageBoxButtons.OKCancel);
        isMessageBoxOpen = false;

        if (result == DialogResult.OK)
        {
            offlineSetTurn();
        }
        else if (result == DialogResult.Cancel)
        {
            Application.Exit();
        }
    }
}
相关问题