Timer doesn't want to start again after it was disabled
c#, multithreading, timer
Solution
As @grzenio said, it appears that your issue has to do with the fact that you are making cross thread calls to a Windows Form Control that was created on a different thread.
If you are using .NET 4.5 (C# 5.0), I would suggest looking at the async/await keywords, a good introduction can be found at Stephen Cleary's Blog
An example of how you could use async and await with your legacy "DoStuff":
private async void _Timer_Tick(object sender, EventArgs e)
{
_Timer.Enabled = false;
await Task.Run((() => DoStuff()));
_Timer.Enabled = true;
}
Things to notice:
- async was added to the Timer_Tick event's signature.
- The await keyword along with Task.Run was used to asynchronously run the DoStuff.
When using these keywords, the DoStuff will be run asynchronously and once DoStuff returns, it will continue on the line after await using the context of the thread that originally called Tick.
Problem
I am writing a simple C# program that attempts to do something every x amount of seconds using System.Forms.Timer The tick event calls a method that starts a new thread and disables the timer, then when the thread is done with its work, it enables the timer again, but the problem is, now it doesn't tick after it's been enabled. ``` static System.Windows.Forms.Timer testtimer = new System.Windows.Forms.Timer(); static void Main() { testtimer.Tick += testtimertick; testtimer.Interval = 5000; testtimer.Enabled = true; testtimer.Start(); while (true) { Application.DoEvents(); //Prevents application from exiting } } private static void testtimertick(object sender, System.EventArgs e) { testtimer.Enabled = false; Thread t = new Thread(dostuff); t.Start(); } private static void dostuff() { //Executes some code testtimer.Enabled = true; //Re enables the timer but it doesn't work testtimer.Start(); } ```