How to use safe threading for a timer(Change timer

2019-08-25 02:54发布

问题:

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?

回答1:

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.



回答2:

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