Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to run 3 levels of timers at the same time in a C# application for example:

T1 will run in the beginning of the application, then on its Tick event, T2 will start and then on the tick event of T2, T3 will start. Finally, on the tick event of T3, something should be done in the main thread of the application

My problem seems to be that the code in the main thread is not working when it is being called by an other thread

What should I do to let the main thread run its functions by a call from other threads?

See Question&Answers more detail:os

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

1 Answer

Most probably the problem is that your main thread requires invocation. If you would run your program in debugger, you should see the Cross-thread operation exception, but at run time this exception check is disabled.

If your main thread is a form, you can handle it with this short code:

 if (InvokeRequired)
 {
    this.Invoke(new Action(() => MyFunction()));
    return;
 }

or .NET 2.0

this.Invoke((MethodInvoker) delegate {MyFunction();});

EDIT: for console application you can try following:

  var mydelegate = new Action<object>(delegate(object param)
  {
    Console.WriteLine(param.ToString());
  });
  mydelegate.Invoke("test");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...