Calling methods in main thread from other threads
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");
user2302005
Updated on November 05, 2020Comments
-
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 almost 11 yearsActually, at last, it will be a unity3D function But currently I am working on the classes
-
causa prima over 9 yearsVS 2013/Resharper 8 tells me I can simpify this to this.Invoke(new Action(MyFunction));
-
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 about 8 yearsHelp please, It is really needed.
-
VladL about 8 years@DreTaX ask the new question, it's hard to help without seeing the code
-
DreTaX about 8 yearsOh wel.. stackoverflow.com/questions/36770367/… will include it
-
knocte over 5 years@VladL: this
Invoke
method, where does it belong to? which class? MSDN please? -
VladL over 5 years@knocte long time ago... but should be Control.Invoke as the method is directly available on the windows form
-
knocte over 5 yearsSystem.Windows.Forms?