Handling Thread communications

I have 2 threads used for serial communications (receive and transmit). I've 
wrestled with a couple of issues off and on for long time.
1. I currently use a ring buffer for the receive thread to put data in. When 
data is received, the thread uses PostMessage() to send a message to the 
application to process the data. This works for the most part except now I 
have encountered a problem when I display a MessageBox() while processing 
received data; I get more messages from the thread that seem to interfere 
with the process. ie the MessageBox displays twice for some reason. When I 
change the PostMessage() to SendMessage() everything works fine.

2. I've used SendMessage() in the thread in the past but always have issues 
when closing the application; sometime the app gets locked when closing 
because the thread has tried to send data.

Can someone recommend some way(s) that I can use SendMessage() from the 
thread and not have the possible loop lock when closing the app?
Thanks 


0
mike
1/13/2006 1:51:27 AM
vc.mfc 33608 articles. 0 followers. Follow

3 Replies
459 Views

Similar Articles

[PageSpeed] 30

Hi,
A try towards the solution.
The SendMessage is synchronous that means once the message is sent
using the SendMessage it will return back only when the processing of
the message is finished at the other end. So in  your case when closing
the application the thread is sending the message using the SendMessage
and other side of the reciever is already out of scope, thereby the
SendMessage hangs and result is locked. My suggestion is to close the
thread which is sending the message or have some logic something like
send the message only if the reciever is active.

Thanks,
Chary.
s.s.chary@google.com

0
s.s.chary (11)
1/13/2006 5:53:25 AM
mike wrote:
> I have 2 threads used for serial communications (receive and transmit). I've
> wrestled with a couple of issues off and on for long time.
> 1. I currently use a ring buffer for the receive thread to put data in. When
> data is received, the thread uses PostMessage() to send a message to the
> application to process the data. This works for the most part except now I
> have encountered a problem when I display a MessageBox() while processing
> received data; I get more messages from the thread that seem to interfere
> with the process. ie the MessageBox displays twice for some reason. When I
> change the PostMessage() to SendMessage() everything works fine.

Well, if your main GUI thread is displaying the messagebox, the worker
thread using serial comm will keep posting messages to it, which means
more messages will be in the queue when you click the OK button.
SendMessage would more than likely lock the serial thread until you
clicked the OK button.

> 2. I've used SendMessage() in the thread in the past but always have issues
> when closing the application; sometime the app gets locked when closing
> because the thread has tried to send data.

You should never use SendMessage on an object that is not running in
the thread. You've ran into the primary reason. If you use send message
from your worker thread, it waits on the other thread to handle the
message before returning. If the GUI thread is locked on something,
say, shutting down, it will never respond because it never returns to
the message loop, and this will cause your worker thread to freeze. You
should use alway use PostMessage instead of SendMessage across threads.


If you have problems with PostMessage causing weird behavior, you may
want to post the code of the message handler in your application as
well as the worker thread where it posts the message to see if we can
help you troubleshoot it.

Josh McFarlane

0
darsant (187)
1/13/2006 5:54:49 PM
You can assume that by using SendMessage you will get lockup.  That's expected behavior.
So don't use it.

Do not display a MessageBox from a worker thread.  Ever.  Do not display a dialog from a
worker thread.  Do not display a MessageBox or Dialog from a UI thread if you can possibly
avoid it.  

There *is* no way to reliably use SendMessage from a thread.  With incredible care you
might possibly get away with it, but it is a very risky long-term solution and should not
even be considered a possibility.
				joe

On Thu, 12 Jan 2006 20:51:27 -0500, "mike" <nospamplease> wrote:

>I have 2 threads used for serial communications (receive and transmit). I've 
>wrestled with a couple of issues off and on for long time.
>1. I currently use a ring buffer for the receive thread to put data in. When 
>data is received, the thread uses PostMessage() to send a message to the 
>application to process the data. This works for the most part except now I 
>have encountered a problem when I display a MessageBox() while processing 
>received data; I get more messages from the thread that seem to interfere 
>with the process. ie the MessageBox displays twice for some reason. When I 
>change the PostMessage() to SendMessage() everything works fine.
>
>2. I've used SendMessage() in the thread in the past but always have issues 
>when closing the application; sometime the app gets locked when closing 
>because the thread has tried to send data.
>
>Can someone recommend some way(s) that I can use SendMessage() from the 
>thread and not have the possible loop lock when closing the app?
>Thanks 
>
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15974)
1/14/2006 7:11:16 AM
Reply:

Similar Artilces:

Exchange 2K to 2K3 migration
I'd like to get some advice on the best approach to handle the STM file during an Inter-Org mailbox move. The Exchange migration wizard will handle the the mailbox but how do you handle the content in the STM file? Thanks. You don't need to worry about it. Mailbox data is stored in both the EDB and STM files. Typically, message content from the Internet will be in the STM file. I'd suspect that when you migrate the mailboxes, all data will be converted to native MAPI format (moved to EDB file) and will then be moved to the new mailbox. -- Ben Winzenz Exchange MVP Me...

Handle to an ActiveX control
Hi... What if I use GetModuleHandle(L"abc.ocx") in the InitInstance() of the of the App class derived from 'COleControlModule'...of the ActiveX control "abc.ocx" ? Will I get the Handle or it will return NULL....? I have encountered controls, in some of them..handle is found and in others its NULL... Wat is the reason behind this behavior..? Can any one explain? "Abby++" <asthana.abhinav@gmail.com> wrote in message news:1174308443.062622.51500@b75g2000hsg.googlegroups.com... > What if I use GetModuleHandle(L"abc.ocx") in the InitI...

invalid handle
hi frds i m very new in vc++ and i m founding too much difficulty in this so plz can any one solve this problem .... actully i m inserting a image in list box using this code ........ everything is returning write thing still it is saying invalid handle after ImageList_Add(hList,m_hBmpNew,0); when i m going to dibug it plz help me BOOL Fun() { // Create 256 color image lists HIMAGELIST hList = ImageList_Create(32,32, ILC_COLOR8 , 8, 1); HBITMAP m_hBmpNew = (HBITMAP) LoadImage( AfxGetInstanceHandle(), // handle to instance "c:\\img.bmp", /...

Intermittent Thread Question
I have an app which uses a worker thread to capture a character stream from a com port. The character stream contains keywords that are used to trigger handshake exchanges and data extraction/storage etc. and the process works well. The character stream is intermittent, that is, there is about 10 minutes of data followed by several minutes of silence. I also have an external trigger that indicates when the character stream is valid. Question: Is it better to let the thread run forever thereby initializing the port DCB once at run time and forget about it or to stop the thread when it's no...

Thunking a 32-bit HANDLE to a 64-bit HANDLE
Currently I am converting a 32-bit WDM driver to a 64-bit KMDF driver that will continue to work with our 32-bit DLL and our customer's 32-bit applications. The sample code for thunking 32-bit items shows the following Buffer->Handle = (HANDLE)Buffer32->Handle; see: http://msdn.microsoft.com/en-us/library/aa489604.aspx Buffer32->Handle is declared as UINT32 Handle The driver compiler issues error number C4312 for this cast. The code that I have adopted (to get it to compile) is: handlerInputs.hEvent = (HANDLE) (ULONG_PTR) p_handlerInputs3...

Daily Bank Sweep
New GP Client that is reconciling for the first time their operating account. We have entered the last reconciled balance and dates as of 12/31/08. Operating account gets swept every night and redeposited the next day. With each sweep interest is calculated. My question is how to handle the last sweep of the month, which is a sweep in transit. We have tried entering as a decrease adjustment (not posting to GL as it should not effect the GL balance). We have also tried entering as an adjustment to see what the effect is. We don't even come close to the bank ending balance. Pl...

Regarding USB communication
Hi, I did serial port communication with the hardware. But I would like to do it by USB port communication, I don't have any idea about it. How we convert Serial communication to USB comm. Satya ...

Handling blank data points
I have a chart which is has "" in a formula to clear contents when not applicable to show error. This results in the chart treating the cell as 0 and therefore ugly result in data point. All other post responses to this type of question suggest using NA() and conditional formation to hide the error.. Unfortunately when this is used this screws up my SUM() and AVG() formulas.. Any other suggestions? Thanks Jo Hi Jo, I don't know if this is the best way but what I have done under similar circumstances is use the #N/A for the chart series data column and then I use a hel...

HANDLES
Hi All, how can I get info concerning the number of handles opened ? Thanks in advance Paolo You can have some information about the handles used by an application using 'Application Verifier' http://msdn.microsoft.com/en-us/library/aa446904.aspx -- Luca Calligaris (MVP-Windows Embedded) lucaDOTcalligarisATeurotechDOTcom www.eurotech.com "Paolo Cremonese" <cremonese@teledata-i.com> ha scritto nel messaggio news:O6rJxu5FLHA.2276@TK2MSFTNGP06.phx.gbl... > Hi All, > > how can I get info concerning the number of handles opened ?...

Handle Dialog Box From GP using Continuum API
Dear All I am working with VS2005, C#, Developer tool kit, GP 10. I am trying to use Continuum API to handle the response of Dialog Box because I can't do that using Developer tool kit. So I did create a new application "Microsoft Dynamics GP Add-in" C# I have this error: "Specified cast is not valid" I build my solution and I add the DLL in this path: C:\Program Files\Microsoft Dynamics\GP\AddIns Please I need your advise please. And I wrote the below Code using System; using System.Collections.Generic; using System.Text; using Microsoft.Dexterity.Bridge; usi...

Slow in handling mailboxes
Outlook 2000 on Windows 2000, at latest levels. I have nine email services defined. Only four of these are set to be checked by Send/Receive; the others are occasional use and are unchecked in the Options/Mail Service list. Outlook is set to check my mailboxes only when I specifically request, not automatically. This a part of my junk-mail prevention strategy. I use MailWasherPro to interact directly with my ISP mailboxes, before the mail ever gets to Outlook Works great! As I added these occasional services, even through Outlook is set not to check them, I found that Send/Receive slowed do...

Thread Problems
Found this from MSDN->codeguru, can't seem to figure out the problem.... class ThreadClass { protected: HANDLE m_hThread; //Thread handle bool m_bActive; //activity indicator DWORD m_lpId; //Thread ID public: ThreadClass(){} virtual ~ThreadClass(){Kill();} //Thread Management bool CreateNewThread() { m_hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_ThreadFunc, (LPVOID) this, 0, (LPDWORD) &m_lpId); if (m_hThread == NULL) return false; m_bActive = true; return true; }; //Wait for thread to end bool Wait() {return (WAIT_OBJECT_0 == WaitForSingleObject(m_hT...

Unable to get the window handle ... Windowless ActiveX controls are not supported
Hello, This exception : System.InvalidOperationException was caught Message="Unable to get the window handle for the 'AxMOSServer' control. Windowless ActiveX controls are not supported." Source="System.Windows.Forms" StackTrace: at System.Windows.Forms.AxHost.EnsureWindowPresent() at System.Windows.Forms.AxHost.InPlaceActivate() at System.Windows.Forms.AxHost.TransitionUpTo(Int32 state) at System.Windows.Forms.AxHost.CreateHandle() at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) ...

Creating and using a GUI thread
Hi, I need to update a control 20 times a second (its a graph control). I want to place the control into a separate GUI thread what simply spins and updates the control on my dialog. How can i do this? I have a class that does the updating and data handling etc, but when i write the data to the control, the GUI freezes because its too quick. Does anyone have an example code to update a control (progress bar for example) in a separate thread? Please help! J On Wed, 19 Apr 2006 10:16:32 +0100, JoeB <joe@nospam.com> wrote: >Hi, > >I need to update a control 20 times...

55 lb. Wide Handle Kettlebell
Price:$65.00 Image: http://specialdealfinder.info/image.php?id=B000QW57OG Best deal: http://specialdealfinder.info/index.php?id=B000QW57OG I bought a 55lb kettlebell as a Christmas gift (from Pacillo's Fitness) for my husband who does a lot of different kinds of strength and endurance training. This product is fantastic. He's used it at least every other day since he's received it. It's just light enough for a beginner to get their feet wet with a few reps, and heavy enough to be challenging for the more advanced user. Also, the handle is wide enough for both his beefy h...

Limit to GDI Handles and User Handles
Hi, My software is a highly interactive application that uses lots of windows with sub windows (a few hundred windows is not an exception). Not all windows are visible at the same time, but at certain moments the user must be able to quickly switch to another window so I keep the relevant windows invisible and make them visible when needed. Due to the structure of the software, it is not possible to decrease the number of windows. Nevertheless I have succeeded to decrease the used pens, brushes, .... Cleaning up the used menu handles and icon handles is planned for the medium- to long-term. ...

Another date handling question variant
Hi, I want to specify time+date and adjust them by timezone, but cannot see how to do this without laborious formulae. I've seen the other time/data tips on this site (v.good thanks), but they don't seem to cover this scenario. what I want to do: Column1: Time, format: dd-mmm-yy [hh]:mm eg: 26-feb-04 03:46 Column2: TZ offset, format: num (0 DP) eg: 5 Column3: Adjusted Time, format: dd-mmm-yy [hh]:mm formula: Col1 + (Col2/24) eg: 26-feb-04 08:46 ie. I want the basic number of TZ offset to increment the original time but that number of hours. Of course, it doesn't work, the e...

How Would You Handle This?
Hello, all. We have a prototype system that's connected via ethernet to a linux machine that's collecting data on an instrument and sending it to the Windows machine. In addition the Windows machine can send commands via the ethernet link to the linux machine. We're using VS6 and MFC on XP. This is a quick and dirty application I've got running as a tabbed dialog application, i.e. a CPropertySheet-derived class with multiple CPropertyPage. The different pages are intended to handle different tasks, e.g. establishing the connection between the machines, changing and retrievi...

thread never calls AfxEndThread
Hi, I have made a simple app with only one button that starts or stop a loop. This loop is actually a thread. In my OnInitDialog I create the thread in a suspended state and when I click on Start I resume the thread and when it's stop I suspend it. Here is the code CTestDlg* pThis; BOOL CTestDlg::OnInitDialog() { .... if (!(m_pThread = AfxBeginThread( thScanCarte, this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED, NULL))) { AfxMessageBox(_T("Cannot create thread")); return false; } .... } /* static */ UINT CTestDlg::thScanCarte( LPVOID pParam ) { pThis =...

How to get the process handle by a window handle which run in the process.
Thanks! GetWindowThreadProcessId Bill Gates wrote: > Thanks! Thanks:> ...

HOWTO Subclass a .NET UserControl's window handle to an MDI EXE
HOWTO Subclass an AtvieX control's window handle to an MDI EXE Please help, I want to make .NET UserControl launch a VC++/MFC/MDI EXE that in turn is fed the UserControl's windows handle via the STDIN, that EXE then uses to subclass, so that its GUI appears in the UserControl's space. Getting the .NET UserControl's windows handle was easy, it was simply "this.Handle". Using the various .NET means to launch an EXE was easy, and to make the .NET UserControl let the EXE inherit the STDIN handles was easy. And I got the EXE to "see/read" the HANDLE on th...

Threads + Static Member Functions
I've created a class that uses a worker thread to perform its dirty work. I have declared the thread procedure as a static member of the class. The thread procedure also calls another static member in the class, ala: CClass { ... BOOL Run(); static UINT ThreadProc(...); static BOOL DoSomething(); } BOOL CClass::DoSomething() { ... } UINT CClass::ThreadProc(...) { ... DoSomething(); } BOOL CClass::Run() { AfxBeginThread(ThreadProc, ...); } What I'm wondering is, are there any potential problems with: a) using a static member function for a thread's main procedure? (as...

why CStatic.m_hWnd not valid after use realtime thread?
Hi All I build an MFC app, and loadlibrary a dll which use high priority (realtime level ) threads for serial communication but after freelibrary the dll, some CStatic and CEdit objects not valid, their m_hWnd becomes to NULL How can I restore these CWnd objects? Is OS release them thanks, waiting onlin ...

Still the same: CAsyncSocket::Receive and CAsyncSocket's threading
Hello, I red all messages, about CAsynchSocket and threading and also Mr Newcomer mvp_tips. And still my problem persist. Shortly I've problem with client socket. My dll library implements protocol to some server. I'm using CAsyncSocket. Dll must be using from dot.Net framework and when I use it simple by calling functions from dll all works fine. But when I create thread and thees all functions are called from thread function OnReceive is not fired. myThreadFunction { CreateObjectsDll(); InitSocketsDll(); ConnectToServerDll(); while ( canrun ){ Thread.Sleep(10)...

Handle Error.
A procedure often Number Overflow. So I put this handler in procedure. Private Sub Hint() On Error GoTo Overflow ....... ' Some codes. Exit Sub Overflow: If (Err = 6) Then ......' Handling error. End If End Sub but if other Error happen. it could be a unhandle error. because I not handing all err number. Hi I suggest a Select Case structure on err number, like this: Sub test() Dim i As Long On Error GoTo ErrHandler i = 23232323232323# ^ 2 MsgBox "i=" & i i = 23 / 0 MsgBox "i=" & i Exit Sub ErrHandler: Select Case Err.Number Case 6 ...