473,666 Members | 2,115 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 12087
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 BackgroundWorke r 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.CallSomeCpp Function(); // 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
CallSomeCppFunc tion instead of it being called directly.
}

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

thrdStrt()
{
COMObject cpp = new COMObject();
cpp.StartProces sing(); // 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] }

CallSomeCppFunc tion()
{
cpp.DoSomeOther Work(); // 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 BackgroundWorke r 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<MethodInv okeractions = new (...);
public void CallSomeCppFunc tion() {
lock(actions) {
actions.Add(Act ualCallSomeCppF unction);
if(actions.Coun t==1) Monitor.Pulse(a ctions); // could be waiting
}
}
private void ActualCallSomeC ppFunction() {
// P/Invoke call to cpp.DoSomeOther Work();
}
public void Start() {
while(running) { // "Stop" condition; volatile or sync-locked
MethodInvoker action;
lock(actions) {
if(actions.Coun t==0) {
Monitor.Wait(ac tions);
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.CallSomeCpp Function();
}
------------------------------- 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.Cre ateControl();
evt.Set();

COMObject cpp = new COMObject();
cpp.StartProces sing(); // 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);

CallSomeCppFunc tion()
{
m_ctrl.BeginInv oke(new ProcessRequests (OnUserRequest) , new
object[] { this, null});
}

OnUserRequest(o bject sender, myparam params)
{
cpp.DoTheRealCp pFunction();
}

Dec 15 '06 #5
"MT" <mt*****@gmail. comwrote in message
news:11******** ************@t4 6g2000cwa.googl egroups.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(thr dStrt));
backgroudthread .SetApartmentSt ate(ApartmentSt ate.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******** ************@t4 6g2000cwa.googl egroups.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.goog legroups.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(thr dStrt));
backgroudthread .SetApartmentSt ate(ApartmentSt ate.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)associat ed 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.goog legroups.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(thr dStrt));
backgroudthread .SetApartmentSt ate(ApartmentSt ate.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.Cre ateControl();
evt.Set();
COMObject cpp = new COMObject();
cpp.StartProces sing(); // 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)associat ed 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
7584
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 looping function the window becomes unmovable and cannot close under its own direction (the upper right "close 'X'") My first attempt to solve the problem was to have the looping function execute as its own thread, the idea being this would...
3
4626
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 and then fires a datareceived event. Within the waitingloop there is a timeout function, but I want the the 'last-time-socket-used' variable set when the socket is finished sending. When I send by System.Net.Sockets.Socket.Send(buffer()) (<--this...
0
4103
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 doesn't always receive a full message, and have coded for EndOFMessage markers etc. But Microsofts documentation implies that if I say BeginSend(buffer, 0, bufferLength...) it will send the entire buffer. Apparently some people think this may not be...
7
3513
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 administrator told me to write the emails to the “pickup directory” instead. I know that JMail can do this in ASP, but how do you do this in asp.net? -- --------------------
3
4292
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 receiver is running within Process1. If I move the receiver into Process2 then its fast. Please can someone explain.
15
2303
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 have read all about delegates, event handlers, Invoke methods etc, however they all seem to have undesribale side effects as I have tried them. The hardest part of the aplication is on exit, well I gues I could just
23
6909
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
5077
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> <zone>BOXING</zone> <status>Running</status> <job>1000139233</job>
7
3503
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 send message to mygui without quitting the ui or closing the
0
8360
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8876
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8784
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8556
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8642
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7387
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5666
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1777
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.