[ACCEPTED]-start a timer from different thread in c#-timer

Accepted answer
Score: 20


You could try to start the timer this way:

Add 4 in form constructor this:

System.Timers.Timer aTimer = new System.Timers.Timer();
 aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
 // Set the Interval to 1 second.
 aTimer.Interval = 1000;

Add 3 this method to Form1:

 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
   //do something with the timer
 }

On button click event 2 add this:

aTimer.Enabled = true;

This timer is already threaded 1 so no need to start a new thread.

Score: 8

It is true what Matías Fidemraizer says. But, there 3 is a work around...

When you have a control 2 on your form that is invokable (eg. a statusbar), just 1 invoke that one!

C# Code sample:

private void Form1_Load(object sender, EventArgs e)
{
    Thread sampleThread = new Thread(delegate()
    {
        // Invoke your control like this
        this.statusStrip1.Invoke(new MethodInvoker(delegate()
        {
            timer1.Start();
        }));
    });
    sampleThread.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    MessageBox.Show("I just ticked!");
}
Score: 3

System.Windows.Forms.Timer works in a single-threaded 12 application.

Check this link:

Remarks says:

A 11 Timer is used to raise an event at user-defined 10 intervals. This Windows timer is designed 9 for a single-threaded environment where 8 UI threads are used to perform processing. It 7 requires that the user code have a UI 6 message pump available and always operate 5 from the same thread, or marshal the call 4 onto another thread.

Read more "Remarks" section 3 and you'll find that Microsoft recommends 2 that you use this timer synchronizing it 1 with the UI thread.

Score: 0

I would use a BackgroundWorker (instead of a raw thread). The 4 main thread would subscribe to the worker's 3 RunWorkerCompleted event: The event fires in your main thread when 2 the thread completes. Use this event handler 1 to restart your timer.

More Related questions