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?
You can use delegate, for example. Show activity on this post. It'll be executed on the main thread, since it's that thread that calls the method. If you want dosomething to run in the separate thread, have it called within run() and store the result in a myThread field for later retrieval.
If you put long running work on the UI thread, you can get ANR errors. If you have multiple threads and put long running work on the non-UI threads, those non-UI threads can't inform the user of what is happening.
A condensed code block is as follows: new Handler(Looper. getMainLooper()). post(new Runnable() { @Override public void run() { // things to do on the main thread } });
The main thread is created automatically when our program is started. To control it we must obtain a reference to it. This can be done by calling the method currentThread( ) which is present in Thread class. This method returns a reference to the thread on which it is called.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With