Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling methods in main thread from other threads

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?

like image 255
user2302005 Avatar asked Jun 15 '13 11:06

user2302005


People also ask

How do you call a thread from another thread?

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.

Why should you avoid to run non UI code on the main thread?

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.

How do I run something on the main thread?

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 } });

What is the name of thread which calls the main method?

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.


1 Answers

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");
like image 106
VladL Avatar answered Sep 29 '22 15:09

VladL