Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
970 views
in Technique[技术] by (71.8m points)

multithreading - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)


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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...