sending msg to message loop of background thread

M

mtsweep

Hi,

I started a background thread to preform some time intensive tasks for
a GUI frontend. This background thread uses a C++ object which requires
a windows message loop so I started one in it by calling
Application.Run(). Now I can see that messages from the C++ libraries
are being processed. But how do I send my own messages to this thread
from the GUI frontend? I tried to use delegates/events/etc but it ends
up either spawning a totalling different thread (BeginInvoke) or
executing on the main GUI thread.

Thanks,
 
M

Marc Gravell

Well, what do you want to do? If you just want a cancel flag, then a
sync-locked flag (or possibly just a volatile field) might do the job.
With BackgroundWorker you can detect cancel requests too. If you have
something more complex, perhaps something simple like a sync-locked
queue (checked periodically by the background thread, or woken via
Monitor.Pulse) might do the trick.

So what do you want to do?

Marc
 
M

MT

I'm not sure exactly what you mean, but what I need to do is for the
GUI or the console app to send an message event to the worker thread's
message loop and then invoke a function on the C++ in that message
handler. I can't use a queue because I also need the same thread to
process the window messages. Unless there is a way to wait for window
messages and queue input? Maybe some sample code will make it
clearer...

static void Main(string[] args)
{
MyObject obj = new MyObject ();
obj.Start();

obj.CallSomeCppFunction(); // see below for problem with this - I
bascially need to have this be sent as a window message to the
background thread (kind of like custom messages in Win32?) so that it
goes through the window message loop and end up calling
CallSomeCppFunction instead of it being called directly.
}

------------------------------- MyObject definition
Start()
{
[spawns off a new thread starting at thrdStrt]
}

thrdStrt()
{
COMObject cpp = new COMObject();
cpp.StartProcessing(); // this starts the c++ object which when
processing posts events back to this thread - let's just say for
example OnUpdateStatus(..)
Application.Run();
}

OnUpdateStatus() { [do some processing] }

CallSomeCppFunction()
{
cpp.DoSomeOtherWork(); // this will fail because all process on the
cpp object needs to be by the thread that created it.
}
 
M

Marc Gravell

I'm sorry: I overlooked the C++ aspect. I was thinking pure C#, in
which case I simply wouldn't use a windows message loop for this
purpose, but simply a producer-consumer queue to manage the various
actions (only 1 shown here) on the C# side, e.g. (untested "notepad"
code):

class MyObject {
// ...
private readonly Queue<MethodInvoker> actions = new (...);
public void CallSomeCppFunction() {
lock(actions) {
actions.Add(ActualCallSomeCppFunction);
if(actions.Count==1) Monitor.Pulse(actions); // could be waiting
}
}
private void ActualCallSomeCppFunction() {
// P/Invoke call to cpp.DoSomeOtherWork();
}
public void Start() {
while(running) { // "Stop" condition; volatile or sync-locked
MethodInvoker action;
lock(actions) {
if(actions.Count==0) {
Monitor.Wait(actions);
continue; // re-check Stop condition, plus release pulsing
thread
}
action = actions.Dequeue();
}
action(); // exedcute on (background) thread, but outside of
queue lock
}
}
}
 
M

MT

Hi,

I afraid I need to have a window message loop because the C++ object is
a COM object and posts messages/events when things occur. (This object
sends messages across the network to a server then returns, and when
the real response comes back posts a messages to the window message
loop.) With the pure queue solution you have those messages won't be
processed by the background thread. Unless I'm missing something?

I have found 1 way to do this by using delegates and creating a dummy
control, but I feel that it is pretty much a hack and would like to see
if there is any other/better way. See below for modified sample code.
So this illustrates what I'm trying to achieve where the main thread
calls a function, when then triggers a window message to be send to the
second thread and gets processed through the message loop.

static void Main(string[] args)
{
MyObject obj = new MyObject ();
obj.Start();

obj.CallSomeCppFunction();
}
------------------------------- MyObject definition
Start()
{
[spawns off a new thread with STA starting at thrdStrt]

evt.WaitOne(); // wait until the new thread creates the Control before
returning
}

Control m_ctrl; // dummy control just so I can use BeginInvoke from the
main thread to post a message to the secondary one.
AutoResetEvent evt; // to ensure Control is created before it is being
used

thrdStrt()
{
this.m_ctrl = new Control(); // create dummy control on secondary
thread
this.m_ctrl.CreateControl();
evt.Set();

COMObject cpp = new COMObject();
cpp.StartProcessing(); // this starts the c++ object which when
processing posts events back to this thread - let's just say for
example OnUpdateStatus(..)
Application.Run();
}

OnUpdateStatus() { [do some processing] } // this gets call by the
COM/cpp object when a response is returned from the network through the
window message loop

public delegate void ProcessRequests(object sender, myparam params);

CallSomeCppFunction()
{
m_ctrl.BeginInvoke(new ProcessRequests(OnUserRequest), new
object[] { this, null});
}

OnUserRequest(object sender, myparam params)
{
cpp.DoTheRealCppFunction();
}
 
W

Willy Denoyette [MVP]

MT said:
Hi,

I afraid I need to have a window message loop because the C++ object is
a COM object and posts messages/events when things occur. (This object
sends messages across the network to a server then returns, and when
the real response comes back posts a messages to the window message
loop.) With the pure queue solution you have those messages won't be
processed by the background thread. Unless I'm missing something?

No you don't need to create a message loop for this, all you have to do is initialize your
thread to enter a STA. You do this by setting the ApartmentState to STA before you start the
thread. Initilaizing a thread for STA will force COM to create a windows and a message
queue, all you need to do is take care that you don't block the thread for instance by
calling Sleep, most other "blocking" API's in the framework are not really blocking, they
are pumping the message queue for COM messages.


Willy.
 
M

MT

Hi Willy,

I do have my thread set to STA. When you do that you still need to call
Application.Run() to get the message loop going. Am I not using the
correct term here? Let me fill in my start function....

Start()
{
backgroudthread = new Thread(new ThreadStart(thrdStrt));
backgroudthread .SetApartmentState(ApartmentState.STA);
backgroudthread .Start();

evt.WaitOne();
}

I am not implementing my own message loop, I'm using the message loop
started by windows per your explanation.

My problem here is that the COM object is on this new background thread
and I don't know how to send it messages from my foreground thread
aside from using the control/delegate hack I did above. In the old
C++/MFC way I could just call Send/PostMessage, but in C# I don't see a
managed way on how to do this.

Thanks for all of your inputs. Keep them coming :)
 
W

Willy Denoyette [MVP]

MT said:
Hi Willy,

I do have my thread set to STA. When you do that you still need to call
Application.Run() to get the message loop going. Am I not using the
correct term here? Let me fill in my start function....

Start()
{
backgroudthread = new Thread(new ThreadStart(thrdStrt));
backgroudthread .SetApartmentState(ApartmentState.STA);
backgroudthread .Start();

evt.WaitOne();
}

That's great , but I would like to see the Thread procedure, above code sys's nothing.
I am not implementing my own message loop, I'm using the message loop
started by windows per your explanation.
The COM message queue and the implicit pumping done by most of the CLR wait API's is only
ment to pump COM messages.
My problem here is that the COM object is on this new background thread
and I don't know how to send it messages from my foreground thread
aside from using the control/delegate hack I did above. In the old
C++/MFC way I could just call Send/PostMessage, but in C# I don't see a
managed way on how to do this.

If you need to send *Window* messages from the main UI thread to your "COM thread", you'l
need a form (all or not hidden)associated with this thread and a WndProc that handles these
messages it's up to you to implement this. The UI thread will need to PInvoke SendMessage to
send a message to the window HANDLE associated with this (hidden) form.
Another option is implement your own queue just like Marc showed you above, and forget the
whole SendMessage stuff.
But, the most appropriate option is to create the COM object on the UI thread, it was
designed for such scenario. If it happens that the COM call blocks the thread for too long a
period, well then it shouldn't have been designed as an "Apartment" threaded object.

Willy.
 
M

MT

I see. Thank you for your explanation.
That's great , but I would like to see the Thread procedure, above code sys's nothing.

The thread procedure was in previous posts. I've copy and pasted it
here.

thrdStrt()
{
this.m_ctrl = new Control(); // create dummy control on secondary
thread
this.m_ctrl.CreateControl();
evt.Set();


COMObject cpp = new COMObject();
cpp.StartProcessing(); // this starts the c++ object which when
processing posts events back to this thread - let's just say for
example OnUpdateStatus(..)
Application.Run();
}
 

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