Calling methods in main thread from other threads

59,737

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");
Share:
59,737
user2302005
Author by

user2302005

Updated on November 05, 2020

Comments

  • user2302005
    user2302005 over 3 years

    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
    user2302005 almost 11 years
    Actually, at last, it will be a unity3D function But currently I am working on the classes
  • causa prima
    causa prima over 9 years
    VS 2013/Resharper 8 tells me I can simpify this to this.Invoke(new Action(MyFunction));
  • DreTaX
    DreTaX about 8 years
    @VladL The console app part, of the delegate thingy doesn't work for me. I defined that variable in a class as static, and I invoke It from a timer, but the Thread is still not the main thread.
  • DreTaX
    DreTaX about 8 years
    Help please, It is really needed.
  • VladL
    VladL about 8 years
    @DreTaX ask the new question, it's hard to help without seeing the code
  • DreTaX
    DreTaX about 8 years
    Oh wel.. stackoverflow.com/questions/36770367/… will include it
  • knocte
    knocte over 5 years
    @VladL: this Invoke method, where does it belong to? which class? MSDN please?
  • VladL
    VladL over 5 years
    @knocte long time ago... but should be Control.Invoke as the method is directly available on the windows form
  • knocte
    knocte over 5 years
    System.Windows.Forms?