如何为计时器使用安全线程(从其他线程更改计时器属性) [英] How to use safe threading for a timer(Change timer properties from different thread)

查看:64
本文介绍了如何为计时器使用安全线程(从其他线程更改计时器属性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使用表单访问备忘录,请使用以下代码

To access a memo on my form,I use the following code

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

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

I'd like to use the same code to enable/disable my timer,but there's no property InvokeRequired for a timer.

    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;
            }
        }
    }

如何从其他线程启用计时器?

How to enable the timer from a different thread?

推荐答案

这"是表单对象吗?

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

Assuming you created the Timer object using the form designer the object is created by the same thread as the one that created the form so checking the form's InvokeRequired property effectively tells you the same thing.

这篇关于如何为计时器使用安全线程(从其他线程更改计时器属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆