views:

402

answers:

1

Hello,

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  A: 

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.

Spencer Ruport
Yes,"this" is a form object,but I'm calling that function from a different thread inside a critical section.
John
That's fine. All the InvokeRequired boolean tells you is if the CurrentThread == ThreadThatCreatedTheObject. The thread that created the form is the same thread that created the timer so this will work.
Spencer Ruport
No,it doesn't.I can't enable the timer.
John