Cross Thread Calls

S

sharp

I know there are better ways to handle what is described below. I am
just looking so see if it possible to make cross thread API calls.

I have a console app that has a main thread and a worker thread. I
would like for the main thread to be able to make an async call to the
worker thread to put messages on a queue. The worker thread is also
responsible for processing messages that are on the queue when it has
free cycles.

The worker thread also need to be responsible for processing command
that the main thread sends.

Is there anyway that the main thread can make direct calls to the
worker thread?
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi sharp,
I have a console app that has a main thread and a worker thread. I
would like for the main thread to be able to make an async call to the
worker thread to put messages on a queue. The worker thread is also
responsible for processing messages that are on the queue when it has
free cycles.

I think you should give more details. What queue? I assume that it is not a
windows message queue as long as you are talking about console application,
but it could be.

Is there anyway that the main thread can make direct calls to the
worker thread?

Strictly speeking you cannot call a thread. However, you can let an object's
method to be executed by particular thread. To do that you should make the
code executed in the worker thread to work in event (message) driven
fashion. In the same way windows' UI works. Then you can wrap method calls
in messages and call a method in the worker thread by posting that message
in the worker thread's message queue.

Examples of where you can find that kind of thread switching:

1. In windows both SendMessages and PostMessages do thread switching. For
PostMessage it's obvious how the thread switching is done. It is not so
obvious for SendMessage, though. SendMessage calls dicrectly winprocs when
the window is created by the caller thread and no switching is necessary.
When the window is created by different thread, though, the winproc has to
be called in the context of the owner thread. That's why when a message is
send accross thread boundaries it goes thru the message queue.

2. Calling COM objects creatred in "Single-Threaded Apartment" (STA) from
different STA thread or from "Mutlithreaded Apartment" (MTA) thread. In this
case before entering the apartment thread has to be switched. The calls goes
thru registered Proxy/Stub and it uses windows messages for thread
switching. That's why STA threads have to have message loop running.

3. Windows Forms' Control.Invoke and Control.BeginInvoke methods use
PostMessage to switch the thread.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top