How to use safe threading for a timer(Change timer

2019-08-25 02:13发布

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

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?

2条回答
爷的心禁止访问
2楼-- · 2019-08-25 02:49

Is "this" a form object?

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-08-25 03:02

Remove the timer from the code like below:

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;
        }
    }
}
查看更多
登录 后发表回答