473,323 Members | 1,551 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,323 software developers and data experts.

sending msg to message loop of background thread

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,

Dec 14 '06 #1
8 12059
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

Dec 14 '06 #2
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.
}

Marc Gravell wrote:
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
Dec 14 '06 #3
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<MethodInvokeractions = 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
}
}
}

Dec 15 '06 #4
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();
}

Dec 15 '06 #5
"MT" <mt*****@gmail.comwrote in message
news:11********************@t46g2000cwa.googlegrou ps.com...
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.
Dec 15 '06 #6
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 :)

Willy Denoyette [MVP] wrote:
"MT" <mt*****@gmail.comwrote in message
news:11********************@t46g2000cwa.googlegrou ps.com...
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.
Dec 15 '06 #7
"MT" <mt*****@gmail.comwrote in message
news:11**********************@73g2000cwn.googlegro ups.com...
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.



Dec 16 '06 #8
MT
I see. Thank you for your explanation.

Willy Denoyette [MVP] wrote:
"MT" <mt*****@gmail.comwrote in message
news:11**********************@73g2000cwn.googlegro ups.com...
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.
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();
}
>
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.
Dec 18 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Shamrokk | last post by:
My application has a loop that needs to run every 2 seconds or so. To acomplish this I used... "Thread.Sleep(2000);" When I run the program it runs fine. Once I press the button that starts the...
3
by: Robert A. van Ginkel | last post by:
Hello Fellow Developer, I use the System.Net.Sockets to send/receive data (no tcpclient/tcplistener), I made a receivethread in my wrapper, the receivethread loops/sleeps while waiting for data...
0
by: Ken Foster | last post by:
In another message thread and also in a message thread on a completely different board, there have been references to BeginSend/EndSend not sending a full message all the time. I know EndReceive...
7
by: Lau | last post by:
I need to send 1000 emails from an asp.net website. Normally I would use System.Web.Mail.MailMessage() to send thru an SMTP server. But the large amount of emails results in a timeout. My server...
3
by: BuddyWork | last post by:
Hello, Could someone please explain why the Socket.Send is slow to send to the same process it sending from. Eg. Process1 calls Socket.Send which sends to the same IP address and port, the...
15
by: colin | last post by:
Hi, Im familiar with c,c++ etc, and Ive spent a week trying to write my first app in c# it works reasonably well, but im having difficulty getting to grips with inter thread signalling etc. I...
23
by: cmdolcet69 | last post by:
How can i add a 5ms delay between bytes i send over to a controller? I have to send 6 bytes in total however in between each byte i need to have a 5ms delay.
10
by: Markgoldin | last post by:
I am sending an XML data from not dontnet process to a .Net via socket listener. Here is a data sample: <VFPData> <serverdata> <coderun>updateFloor</coderun> <area>MD2</area>...
7
by: gordon | last post by:
is it possible to send a message to the gui instance while the Tk event loop is running?I mean after i create a gui object like root=Tk() mygui=SomeUI(root) and call root.mainloop() can i...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.