Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable a timer from a different thread/class

Tags:

c#

winforms

timer

Original post: How to access a timer from another class in C#

I tried everything.

-Event

-Invoke can't be done,because Timers don't have InvokeRequired property.

-Public/internal property

Nothing worked,the code is being executed,the timer.Enabled property is being set to "true" ,but it doesn't Tick.If I call the event or just change the property from the form class in a NON-static method - it does tick and works.

I never knew it would take me a day and probably more to acquire how to use a decent timer.

If there's no way to do this,is there anything else I can use that works similiar to the timer(delay,enable/disable)?

like image 817
Ivan Prodanov Avatar asked Dec 03 '22 15:12

Ivan Prodanov


2 Answers

You should use the Timer class from the System.Timers namespace, and not the WinForms Timer control, if you want multi-threading support. Check the MSDN documentation for the WinForms Timer control for more information:

http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

like image 94
David M Avatar answered Dec 22 '22 01:12

David M


You don't need to check InvokeRequired on the Control iteself, you can check the property on the class e.g.:

if (this.InvokeRequired) 
{ 
    BeginInvoke(new MyDelegate(delegate()
    {
        timer.Enabled = true;
    }));
}
like image 21
Seibar Avatar answered Dec 21 '22 23:12

Seibar