【问题标题】:How to use safe threading for a timer(Change timer properties from different thread)如何为计时器使用安全线程(从不同线程更改计时器属性)
【发布时间】:2009-04-07 10:56:28
【问题描述】:

要访问我的表单上的备忘录,我使用以下代码

    public string TextValue
    {
        set
        {
            if (this.Memo.InvokeRequired)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    this.Memo.Text += value + "\n";
                });
            }
            else
            {
                this.Memo.Text += value + "\n";
            }
        }
    }

我想使用相同的代码来启用/禁用我的计时器,但是没有属性 InvokeRequired 用于计时器。

    public int Timer
    {
        set
        {
            if (this.timer.InvokeRequired) //?? No such thing
            {
                this.Invoke((MethodInvoker)delegate
                {
                    if (value == 1)
                        this.timer.Enabled = true;
                    else
                        this.timer.Enabled = false;
                });
            }
            else
            {
                if (value == 1)
                    this.timer.Enabled = true;
                else
                    this.timer.Enabled = false;
            }
        }
    }

如何从不同的线程启用计时器?

【问题讨论】:

    标签: c# winforms multithreading timer


    【解决方案1】:

    “this”是表单对象吗?

    假设您使用表单设计器创建了 Timer 对象,该对象是由与创建表单的线程相同的线程创建的,因此检查表单的 InvokeRequired 属性可以有效地告诉您同样的事情。

    【讨论】:

    • 是的,"this" 是一个表单对象,但我是从关键部分内的不同线程调用该函数。
    • 没关系。所有 InvokeRequired 布尔值都告诉您 CurrentThread == ThreadThatCreatedTheObject。创建表单的线程与创建计时器的线程相同,因此这将起作用。
    • 不,它没有。我无法启用计时器。
    【解决方案2】:

    从下面的代码中删除计时器:

    public int Timer
    {
        set
        {
            if (this.InvokeRequired) 
            {
                this.Invoke((MethodInvoker)delegate
                {
                    if (value == 1)
                        this.timer.Enabled = true;
                    else
                        this.timer.Enabled = false;
                });
            }
            else
            {
                if (value == 1)
                    this.timer.Enabled = true;
                else
                    this.timer.Enabled = false;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多