18

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?

user2302005
  • 227
  • 1
  • 2
  • 7
  • Can you show us your code ? – Kurubaran Jun 15 '13 at 11:24
  • What is the **business* problem you are trying to solve? – Pieter Geerkens Jun 15 '13 at 11:28
  • Class C1 { Timer T1; C2 c2; OnT1Tick() { c2.T2.start() } } Class C2 { Timer T2 C3 c3; OnT2Tick() { c3.T3.start } } Class C3 { Timer T3 OnT3Tick() { system.console.write ("something"); } } The problem is that the system.console.write is being called from the main thread and each timer is creating a new thread – user2302005 Jun 15 '13 at 11:30
  • 1
    @user2302005 please edit your question and copy/paste the code from the ide. nowhere i see `new` keyword. are you sure even the first timer is firing? – inquisitive Jun 15 '13 at 11:51

1 Answers1

32

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");
VladL
  • 12,769
  • 10
  • 63
  • 83