1

我正在尝试在文本框中运行计时器,但我没有任何运气。

这是我正在使用的代码:

private static System.Timers.Timer timer;
...
private void StartBtn_Click(object sender, EventArgs e)
{
    timer = new System.Timers.Timer(1000);
    timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    timer.Enabled = true;
}
...
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    TimeTb.Text = e.SignalTime.ToString();
}

但什么也没有发生。

我试过这个:

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    MessageBox.Show(e.SignalTime.ToString(), 
    "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}

它工作得很好。任何人都知道为什么它不适用于我的文本框?

4

6 回答 6

4

Elapsed Event 在与 UI 不同的线程上运行。它不允许从不同的线程操作 UI 对象,并且异常应该出现在您的 EventHandler 中。由于您不在那里处理异常,因此您不会注意到它。

StartBtn_Click将 Timer 的SynchronizingObject属性设置为此(表单)。然后elapsed Event会与主线程同步。

于 2013-09-23T12:26:04.900 回答
1

转一try catch转,OnTimedEvent看看线程是否有任何问题。如果有,请尝试使用System.Windows.Forms.Timerwhich 可以解决跨线程问题。

http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

就像声明的那样:

实现一个以用户定义的时间间隔引发事件的计时器。此计时器针对在 Windows 窗体应用程序中的使用进行了优化,并且必须在窗口中使用。

于 2013-09-23T12:26:30.783 回答
1

您的 OnTimedEvent 回调将不会在 UI 线程上调用,因此您将在那里尝试设置文本框文本时遇到异常。因此,您需要将事件处理程序更改为如下所示:

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
  if (TimeTb.InvokeRequired)
  {
    TimeTb.Invoke((MethodInvoker)delegate
                {
                  OnTimedEvent(source, e);
                });

  }

  TimeTb.Text = e.SignalTime.ToString();
}
于 2013-09-23T12:28:49.243 回答
1

也许你应该先启动计时器。

看一眼:

http://msdn.microsoft.com/en-us/library/system.timers.timer.start.aspx

所以添加:

timer.Start();
于 2013-09-23T12:18:37.973 回答
0

你可以做类似的事情

private void Button_Click(object sender, RoutedEventArgs e)
    {
        this._timer = new DispatcherTimer();
        this._timer.Interval = TimeSpan.FromMilliseconds(1);
        this._timer.Tick += new EventHandler(_timer_Tick);
        _timer.Start();
    }

void _timer_Tick(object sender, EventArgs e)
{
    t= t.Add(TimeSpan.FromMilliseconds(1));
    textBox.Text = t.Hours + ":" + t.Minutes + ":" + t.Seconds + ":" + t.Milliseconds;
}

编辑 :

如何添加程序集:WindowsBase

在此处输入图像描述

于 2013-09-23T12:20:40.743 回答
0

尽管不推荐使用Application.DoEvents();afterTimeTb.Text = e.SignalTime.ToString();可能会起作用(使用 Application.DoEvents())。

于 2013-09-23T12:20:41.427 回答