属性 中的 C# 定时器

C# Timer inside a property

我正在尝试为复选框实现一个计时器。复选框的绑定是使用 CaptureColorBind 属性 完成的。当我单击捕获颜色复选框 (captureColor = true) 时,需要选中它 5 秒,然后需要取消选中该复选框。我正在尝试在计时器之前和之后打印日期时间以进行验证。它正确地打印了之前的时间,但是我在经过的事件处理程序中打印的日期时间被打印了 n 次,具体取决于我单击捕获颜色复选框的次数。那是我第一次点击,它打印一次日期和时间,我第二次点击,它打印两次,依此类推。不确定我做错了什么。

private System.Timers.Timer timer = new System.Timers.Timer();
public bool CaptureColorBind
    {
        get
        {
            return this.captureColor;
        }

        set
        {
            this.captureColor = value;
            if (captureColor == true)
            {
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine();
                timer.Elapsed += new ElapsedEventHandler(capturecolor_timer);
                timer.Interval = 5000;
                timer.Enabled = true;
            }
            if (null != this.PropertyChanged)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("CaptureColorBind"));
            }
        }
    }

    // Timer for capturecolor checkbox      
    private void capturecolor_timer(object sender, ElapsedEventArgs e)
    {
            timer.Enabled = false;
            this.captureColor = false;
            //this.colorCheckbox.IsChecked = false;
            Console.WriteLine(DateTime.Now.ToString());
            Console.WriteLine();
            if (null != this.PropertyChanged)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("CaptureColorBind"));
            }
    }

每次设置值时,您都会添加一个新的事件处理程序。您应该只添加一次。

尝试在对象的构造函数中添加事件处理程序,使其只设置一次,并在设置 属性 时重新启用计时器。

private System.Timers.Timer timer = new System.Timers.Timer();
public MyObject()
{
    timer.Elapsed += new ElapsedEventHandler(capturecolor_timer);
    timer.Interval = 5000;
}