0

在用户定义的类中,我有一个计时器,但它不会在我启动时启动Timer.Enabled.

用户定义的类:

  TSerialIndicator = public class
  private
    method TxTimerEvent(Sender:System.Object; e:System.EventArgs);
  public    
    Txlight:Label;
    Txtimer:System.Windows.Forms.Timer;
    constructor(mform:Form);
    method Transmit;
    method Receive;
  end;

这是构造函数:

constructor TSerialIndicator(mform:Form);
begin
    TxLight := new Label;

    TxLight.AutoSize := false;

    TxLight.BorderStyle := BorderStyle.FixedSingle;

    TxLight.Location := new point(52,163);

    TxLight.Width := 20;
    TxLight.Height := 20;

    mform.Controls.Add(TxLight);

    TxTimer := new System.Windows.Forms.Timer;
    TxTimer.Interval:=1;

    TxTimer.Enabled:=false;
    TxTimer.Tick += new System.EventHandler(@TxTimerEvent);

    TxLight.BackColor := Color.Black;
end;

这是定义的传输方法:

method TSerialIndicator.Transmit;
begin
  TxLight.BackColor := Color.Red;

  if TxTimer.Enabled = false then
     TxTimer.Enabled:=true;
end;

这是定义的 TxTimerEvent:

method TSerialIndicator.TxTimerEvent(Sender:System.Object; e:System.EventArgs);
begin
    TxLight.BackColor := Color.Black;
    TxTimer.Enabled:=false;
end;

以下是它的创建和使用方式:

Slight := new TSerialIndicator(self);
Slight.Transmit;

当我从程序的其他部分调用 Transmit 时,它会做它的事情,但 TxTimerEvent 永远不会触发。我什至尝试过启动/停止它的方法。它仍然没有执行它的 Tick 事件。但是,我确实注意到,当我在构造函数中启用计时器时,它确实会触发一次 TxTimerEvent。

我究竟做错了什么?

提前致谢,

4

1 回答 1

4

对于像“Transmit”和“Receive”这样的方法名称,很可能涉及到一个线程。就像运行 SerialPort 的 DataReceived 事件的线程池线程一样。或者由于 System.Timers.Timer 的 Elapsed 事件而运行的代码。等等。

在这样的工作线程中将 System.Windows.Forms.Timer 的 Enabled 属性设置为 true 是行不通的,它不是线程安全的类。它做它通常做的事,创建一个隐藏窗口,使用 Windows 的 SetTimer() 方法来触发 Tick 事件。但是该窗口是在不发送消息循环的线程上创建的。因此 Windows 不会生成 WM_TIMER 消息。

根据需要使用 Control.Begin/Invoke() 以确保与计时器或控件相关的任何代码在 UI 线程上运行。

于 2012-11-09T16:54:05.777 回答