Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start a timer from different thread in c#

Hi i have stepped into some problem related to timer. hope somebody can help..

  1. I have a windows form containing a button
  2. when i click on that button i start a parameterised thread
Thread thread1 = new Thread(new ParameterizedThreadStart( execute2));
thread1.Start(externalFileParams);
  1. the code inside the thread executes very well
  2. at the last line of this thread i start a timer

.

public void execute2(Object ob)
{
    if (ob is ExternalFileParams)
    {
        if (boolean_variable== true)
          executeMyMethod();//this also executes very well if condition is true
        else
        {
            timer1.enabled = true;
            timer1.start();
            }
        }
    }
}

5 but the tick event of the timer is not fired

I am working on VS2008 3.5 framework. I have dragged the timer from toolbox and set its Interval to 300 also tried to set Enabled true/false method is timer1_Tick(Object sender , EventArgs e) but its not fired

can anybody suggest what I am doing wrong?

like image 654
Swati Avatar asked Apr 20 '11 07:04

Swati


2 Answers


You could try to start the timer this way:

Add 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 this method to Form1:

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

On button click event add this:

aTimer.Enabled = true;

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

like image 76
Gabriel Avatar answered Oct 11 '22 14:10

Gabriel


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

When you have a control on your form that is invokable (eg. a statusbar), just 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!");
}
like image 42
321X Avatar answered Oct 11 '22 13:10

321X