Sleep() in Win32 makes program unresponsive - c++

Basically exactly what the title says. I would like to update the text that a button contains every 1 second when the user presses that particular button. I have noted that when the program doesn't have focus it works alright and the text refreshes correctly but when I am hovering over the program or when I am trying to click on it's menu Windows inform me that the program is unresponsive and asks me if I want it terminated. When the loop finishes the program returns to its normal state. Also any action I might have done (like moving it around or closing it) while it was Sleep()-ing is executed after the loop. Here is a bit of code:
case ID_BUTTON_START:
// Code executed when pressing Start Button.
char startButtonText[30]; // Storing next loop text
for (int i=5; i>0; i--)
{
sprintf(startButtonText, "Starting in ... %d", i);
SendMessage(hwndButtonStart, WM_SETTEXT, 0, (LPARAM)(startButtonText));
Sleep(1000);
}
Is this normal? If not what's causing this?

The WndProc does not process messages asynchronously within an application which means all messages are expected to be handled quickly and a return value delivered immediately. You must not Sleep in the UI thread since it will block other UI events from being processed. Any heavy work or synchronous requests/jobs which are likely to take a long time should be performed in worker threads. There are at least three viable options:
Create a new (worker thread) for the task.
If the task is likely to be done often, use a thread pool instead.
Set and subscribe to timer events.

I think the call to Sleep() might be keeping you from returning from the WndProc, so your application is not processing the incomming events for 5 secs. I suggest you try to subscribe to 5 timer events in 1s, 2s,..., 5s. Like when the timer message is recieved the button text must change. I don't know a way how to do that off the top of my head.

Related

buttons on wxWidgets

I am programming a GUI with wxWidgets. I got a button to open a serial port and receive data. In there is a while(1) loop to constantly receive the data.
Now I want to do a "Disconnect" button to stop receiving.
Is there an event handler or a callback function to interrupt the while and jump out of the loop from the first button, when I press another button?
A wxButton sends a message when it is clicked. Create a handler for this message where you do your "interrruption".
Now, a loop can be only exited from its inner guts. I mean, inside the loop you should check a flag, and depending on the value of this flag continue or exit.
My advice is that you create a worker thread. When the button "connect" is clicked then you create the thread that receives data.
This thread checks an extern flag and finishes depending on the value of the flag.
The "disconnect" button click-handler just sets that extern flag to a value that makes the thread exits when it checks that flag.
Take a look at the thread sample provided with wxWidgets sources.
If you have a while(1) loop in the callback function for "button pressed", you will hang the UI. Callback functions must return quickly.
The quickest solution is to put the while(1) loop into a worker thread. That way your GUI won't hang.
The next problem is how to stop the loop. That's quite easy. Change the loop into:
while (keep_going.load()) {
....
where keep_going is of type std::atomic_bool. Then your "stop" button just calls keep_going.store(false).

SendMessage WM_COPYDATA between two processes [duplicate]

Basically exactly what the title says. I would like to update the text that a button contains every 1 second when the user presses that particular button. I have noted that when the program doesn't have focus it works alright and the text refreshes correctly but when I am hovering over the program or when I am trying to click on it's menu Windows inform me that the program is unresponsive and asks me if I want it terminated. When the loop finishes the program returns to its normal state. Also any action I might have done (like moving it around or closing it) while it was Sleep()-ing is executed after the loop. Here is a bit of code:
case ID_BUTTON_START:
// Code executed when pressing Start Button.
char startButtonText[30]; // Storing next loop text
for (int i=5; i>0; i--)
{
sprintf(startButtonText, "Starting in ... %d", i);
SendMessage(hwndButtonStart, WM_SETTEXT, 0, (LPARAM)(startButtonText));
Sleep(1000);
}
Is this normal? If not what's causing this?
The WndProc does not process messages asynchronously within an application which means all messages are expected to be handled quickly and a return value delivered immediately. You must not Sleep in the UI thread since it will block other UI events from being processed. Any heavy work or synchronous requests/jobs which are likely to take a long time should be performed in worker threads. There are at least three viable options:
Create a new (worker thread) for the task.
If the task is likely to be done often, use a thread pool instead.
Set and subscribe to timer events.
I think the call to Sleep() might be keeping you from returning from the WndProc, so your application is not processing the incomming events for 5 secs. I suggest you try to subscribe to 5 timer events in 1s, 2s,..., 5s. Like when the timer message is recieved the button text must change. I don't know a way how to do that off the top of my head.

ProcessMessages on OnShow Event c++ builder

I'm using c++ builder (bcb6) and on:
FormShow
event there is:
Application->ProcessMessages
I would like to know what exactly the responsibility of:
Application->ProcessMessages
What exactly it did? and when we shall use by that? when it can cause exp.?
Thanks!
The BDS 2006 IDE help states for Application->ProcessMessages this:
Interrupts the execution of an application so that it can process the message queue.
Call ProcessMessages to permit the application to process messages that are currently in the message queue. ProcessMessages cycles the Windows message loop until it is empty, and then returns control to the application.
Neglecting message processing affects only the application calling ProcessMessages, not other applications. In lengthy operations, calling ProcessMessages periodically allows the application to respond to paint and other messages.
ProcessMessages does not allow the application to go idle, whereas HandleMessage does.
so what for it is?
It allows to respond to Windows messages in case your app is blocking normal WindProc operation (inside VCL). For example if you got some lengthy computation on some event that takes minutes the application would freeze (can not click,move,resize,redraw,... until operation is done). If you once in a time call ProcessMessages from that long loop (timers would also not work during that time) that will allow to make your app responsive during this time... so it will not freeze.
I usually use threads or OnIdle event instead for such computations so the main App is not blocked at all.
I am reluctant to believe that OnShow is called during such blocking. I would place the ProcessMessages inside the computation that blocks the App (if the computations is inside the OnShow then it is OK otherwise it would be useless. Anyway OnShow is called only if your Form is turning to Visible do not mistake it for OnActivate or OnPaint.
small example
Create empty form app and place 2 buttons in it (btStart,btStop) then create on click event for them as following:
//---------------------------------------------------------------------------
bool go=false;
//---------------------------------------------------------------------------
void __fastcall TForm1::btStartClick(TObject *Sender)
{
int i=0;
for (go=true;go;)
{
Caption=i; i++;
Application->ProcessMessages();
Sleep(100);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::btStopClick(TObject *Sender)
{
go=false;
}
//---------------------------------------------------------------------------
When you start app and click btStart it will start incrementing integer in Caption field of the Form1 and stop when you click btStop. during counting the App is still responsive (can click,move,resize,...). You need to stop before closing App is possible (destructors wait for returning from all events). if you rem out the Application->ProcessMessages(); then the App will count but will never stop because you can not click on btStop due to the freeze. To close click on the IDE and press CTRL+F2.
Hope it clears things a bit.

Mouse jiggling / message processing loop

I have written a multithreaded program which does some thinking and prints out some diagnostics along the way. I have noticed that if I jiggle the mouse while the program is running then the program runs quicker. Now I could go in to detail here about how exactly I'm printing... but I will hold off just for now because I've noticed that in many other programs, things happen faster if the mouse is jiggled, I wonder if there is some classic error that many people have made in which the message loop is somehow slowed down by a non-moving mouse.
EDIT: My method of "printing" is as follows... I have a rich edit control window to display text. When I want to print something, I append the new text on to the existing text within the window and then redraw the window with SendMessage(,WM_PAINT,0,0).
Actually its a bit more complicated, I have multiple rich edit control windows, one for each thread (4 threads on my 4-core PC). A rough outline of my "my_printf()" is as follows:
void _cdecl my_printf(char *the_text_to_add)
{
EnterCriticalSection(&my_printf_critsec);
GetWindowText(...); // get the existing text
SetWindowText(...); // append the_text_to_add
SendMessage(...WM_PAINT...);
LeaveCriticalSection(&my_printf_critsec);
}
I should point out that I have been using this method of printing for years in a non-multithreaded program without even noticing any interaction with mouse-jiggling.
EDIT: Ok, here's my entire messageloop that runs on the root thread while the child threads do their work. The child threads call my_printf() to report on their progress.
for(;;)
{
DWORD dwWake;
MSG msg;
dwWake = MsgWaitForMultipleObjects(
current_size_of_handle_list,
hThrd,
FALSE,
INFINITE,
QS_ALLEVENTS);
if (dwWake >= WAIT_OBJECT_0 && dwWake < (WAIT_OBJECT_0 + current_size_of_handle_list))
{
int index;
index = dwWake - WAIT_OBJECT_0;
int j;
for (j = index+1;j < current_size_of_handle_list;j++)
{
hThrd[j-1] = hThrd[j];
}
current_size_of_handle_list--;
if (current_size_of_handle_list == 0)
{
break;
}
}
else if (dwWake == (WAIT_OBJECT_0 + current_size_of_handle_list))
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else if (dwWake == WAIT_TIMEOUT)
{
printmessage("TIMEOUT!");
}
else
{
printmessage("Goof!");
}
}
EDIT: Solved!
This may be an ugly solution - but I just changed the timeout from infinite to 20ms, then in the if (dwWake == WAIT_TIMEOUT) section I swapped printmessage("TIMEOUT!"); for:
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
I'm not closing this question yet because I'd still like to know why the original code did not work all by itself.
i can see 3 problems here:
the documentation for WM_PAINT says: The WM_PAINT message is generated by the system and should not be sent by an application. unfortunately i don't know any workaround, but i think SetWindowText() will take care of repainting the window, so this call may be useless.
SendMessage() is a blocking call and does not return until the message has been processed by the application. since painting may take a while to be processed, your program is likely to get hanged in your critical section, especially when considering my 3rd point. PostMessage() would be much better here, since you have no reason to need your window to be repainted "right now".
you are using QS_ALLEVENTS in MsgWaitForMultipleObjects(), but this mask DOES NOT include the QS_SENDMESSAGE flag. thus your SendMessage() call is likely ignored and does not wake your thread. you should be using QS_ALLINPUT.
can you check the behavior of your application with an INFINITE timeout and the above 3 modifications included ?
If I remember correctly, WM_PAINT is a very low priority message, and will only get relayed when the message queue is otherwise empty. Also, Windows will coalesce multiple WM_PAINT messages into one. I could see the mouse movement resulting in fewer redraw events, each handling a larger update, thus improving performance.
Well I can't totally help you because we don't have enough info but I had a similar problem where my application would not refresh unless I moved the mouse or after some (not unsignificant) delay.
When investigating the problem I found that basically, the GUI thread will sleep if there is no more messages to process. Jiggling the mouse will create new windows messages to be sent to the windows, waking the thread from sleep.
My problem was that I was doing my processing in the OnIdle (MFC, not sure about you) function, and that, after doing the processing one time, the thread would go to sleep.
I don't think that is your problem since you seems to post a windows message (WM_PAINT) from your thread, what I wasn't doing in my case (which should wake up the gui thread) but maybe this can help you get in the right direction to solve your problem?
Edit: I though about it a little, maybe there is a special case for WM_PAINT (like you forget to call Invalidate or something, I'm not an expert in windows programming) so maybe try to post another message like WM_USER to your application and see if it fix your problem (this should be sure to wake up the gui thread I think). Also posting the full call to the SendMessage function could help.
Edit2: Well, after seeing your comment to Kelly French above you seems to have exactly the same symptoms I had so I would guess that, for whatever reason, your call to PostMessage do not seems to wake up the gui thread or something similar. What are you passing for first argument to PostMessage? What I did in my case was to call PostMessage with argument WM_USER, 0, 0 to my app. You can also try the PostThreadMessage variant while keeping the current threadID of the main thread in a variable (see GetCurrentThreadId).
Also you could try to call Invalidate on your object. Windows keeps memory of if an object need to be repainted and will not do it if it is not needed. I do not know if a direct call to WM_PAINT override this or not.
Well that's all I can think of. At least you found a fix even if it is not the most elegant.
Are you completely sure that the program really runs faster? Or is it output that is refreshed more frequently?
Are you using SendMessage or PostMessage? I'm curious if perhaps switching to the other will make things work "better" in this particular environment.
Taken from developerfusion:
There’s another similar API which
works exactly like SendMessage and
that is PostMessage API. Both require
same parameters but there’s a slight
difference. When a message is sent to
a window with SendMessage, the window
procedure is called and the calling
program (or thread) waits for the
message to be processed and replied
back, and until then the calling
program does not resume its
processing. One thing is wrong with
this approach however, that is if the
program that is busy carrying out long
instructions or a program that has
been hung and hence no time to respond
to the message will in turn hang your
program too because your program will
be waiting for a reply that may never
arrive. The solution to this is to use
PostMessage instead of SendMessage.
PostMessage on the otherhand returns
to the calling program immediately
without waiting for the thread to
process the message, hence saving your
program from hanging. Which of them
you have to use depends on your
requirement.
Is your GUI window maximized? Does it happen whether the mouse movement happens over your app window or over some other window like another app or the desktop? When the mouse moves over your app, the mouse_move messages get sent to your message queue. This may wake up the thread or be forcing a WM_PAINT message.
I doubt that the printing is actually going faster. I suspect that the increased number of messages caused by the mouse movement is forcing more window invalidation events so the text updates are happening on a more granular basis. When the mouse isn't being moved does the printing happen in larger blocks, say blocks of 20 characters vs 5 characters at a time?
Could you clarify what you mean by faster printing? Is it absolute, like 100 characters per minute vs 20 characters per minute? Or is it more like 100 characters per minute either way but they show up in blocks when the mouse is still?
One possibility is that you are seeing the effect of the OS doing thread priority boosting / retarding for certain GUI messages.
I am assuming you have one ”GUI & Other Stuff” thread, and multiple worker threads. When there is no GUI activity, the “Other Stuff” thread goes to a lower priority. When you wiggle the mouse or timeout, the “Other Stuff” thread goes to a higher priority.
Changing the worker threads to a lower priority and then wiggling the mouse, would confirm or refute this.
I think it has to do with processing in foreground and background. If the operating system thinks your window is not top priority it shifts your job to background. If you are forcing the window to be on top, it will put all its resources to work on your window and drops the other items it is working on. Its real and its been here since DOS. http://en.wikipedia.org/wiki/Foreground-background You might try calling the following at critical times in your code.
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long

Avoiding "(Not Responding)" label in windows while processing lots of data in one lump

I occasionally need to process a large amount of data from one package off the network, which takes sufficiently long that when the user tries to interact with the application windows adds the "(Not Responding)" string to the window title. I am aware this is because the processing is being done within a call to handle a message (some way up the stack) and therefore is blocking the message pump. I'm also aware the ideal way to deal with this is to process the data asynchronously in a separate thread so the pump can continue running, however this is a LARGE desktop application which is single threaded from top to toe and safely spinning this processing off is not feasible in our time frame.
So with that in mind, is there by any chance a way I can at least avoid the "not responding" moniker (which to most users reads as "has crashed") by telling windows my application is about to be busy before I begin the work? I believe there is something along these lines when responding to a request to close, one can keep asking windows for more time to avoid it proclaiming that your not "closing in a timely fashion"
I should add this is a C++ MFC application.
I don't think the Windows API can help you here.
Alternatively, how about showing a dialog box with a progress bar and make it run in a separate thread?
A text like "This operation may take half an hour" on the dialog box may be appropriate too.
Ok, firstly I upvoted Frederick's post because like it or not, the second thread is probably the best way to go.
However, if you really don't want to go down this road, you could manually pump the message queue within your apps inner loop. Something like this;
int Refresh()
{
MSG msg;
if (PeekMessage (&msg, NULL, 0, 0,PM_NOREMOVE))
if ((msg.message == WM_QUIT)
||(msg.message == WM_CLOSE)
||(msg.message == WM_DESTROY)
||(msg.message == WM_NCDESTROY)
||(msg.message == WM_HSCROLL)
||(msg.message == WM_VSCROLL)
)
return(1);
if (PeekMessage (&msg, NULL, 0, 0,PM_REMOVE))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
return(0);
}
This is actually a piece of code I used prior to rewriting something similar as a seperate thread. Basically I have a look at the queue, filter out unwanted messages, and post on the rest. It works to an extent, but caused some occasional nasty side effects, hence the rewrite.
You don't have to actually do anything with the messages from PeekMessage. Just call PeekMessage, you don't even have to remove anything from the queue or process it. As long as it is called every 5 seconds or so, it will cause windows to think the process is still responsive.
An alternative idea is to have a separate process/thread that will appear in the notification tray and inform the user that the process is busy waiting for an internal operation to complete. You'll see these in the later versions of Visual Studio, SQL Server Management Studio, etc.
Win32 has a method for this in user32.dll.
DisableProcessWindowsGhosting()
Disables the window ghosting feature for the calling GUI process. Window ghosting is a Windows Manager feature that lets the user minimize, move, or close the main window of an application that is not responding.
In addition to the above documented behavior, I also verified here (in a C# application) that this Win32 call also prevents the Not Responding label from appearing on the window as desired.
I found this via the C# answer to similar question here: https://stackoverflow.com/a/15380821/29152.
If you fork off a thread you're most likely worried about some other user action happening which may depend on the result of the long running operation (yeah, concurrency). So expanding on what Fredrick said, if you do spin off a new thread and put up a progress bar, you could lock the focus onto the progress bar to stop a user from interacting with the rest of the application. That should be enough to implement a really simple second thread without really having to worry about concurrency because you're essentially locking out the rest of the app by disabling user interation.
You'll need to interleave the processing with message handling somehow. If threads are out of the question, you might want to look at splitting the processing into multiple phases. One way to do this is to do some processing when you first receive the packet, then post a message to the application saying "continue processing here". When the application receives the "continue processing here" message, it will do some more processing, and either send another "continue processing here" message or finish up.
There are a couple of considerations though:
You need to make sure that the state of the application is consistent every time you post a message to yourself and defer to the message loop, as other message handling might happen in the mean-time. This can be done e.g. by only changing the state in the final processing phase.
Another packet might arrive while you are still processing the first packet. If changing the order of processing would be bad for the application, you could handle this by e.g. posting a "remind me to process this packet later" message when this happens.
I don't know whether this would be feasible within the design of your application, but it would be one way to solve the problem.
If you are unwilling to spawn a worker thread, but you can break the long-running task down into smaller parts, you can do the processing in MFC's CWinApp::OnIdle. This function gets called from within the message pump loop whenever there are no Windows messages waiting. As long as the work you do in each OnIdle call is sufficiently short, you keep your app responsive.
Assuming that it is the processing of the data that is taking up all the time and not the receiving (and you're serious about avoiding a thread - which is fine IMOHO) of the data you could:
In the function that you are currently handling the message, create a modal dialog that shows a "please wait" message (or make it hidden, small, whatever...). Copy (or send a pointer, etc...) the data you're processing to a member variable of that dialog.
In the modal dialog post a user-defined message to yourself to process the data.
In the dialog's message handler, handle one "unit" of work. Keep track what the next "unit" of work is. Post the same message again.
Repeat this post-message "loop" until done. Close your dialog.
The nature of the modal dialog will keep you're application "responsive", with minimal interruption or change to how the application worked previously. Reentrancy can be a problem with modal loops, especially if any of this is involved with a WM_PAINT message. (anyone ever assert inside painting code? good times, good times...)
The dialog could even have a cancel button if you'd like.
I encountered the exact same problem.
Since I dont consider the other answers appealing/straightforward I decided to post this.
Short description and some context:
I am saving data from a grid into a database, and this process can take a while. So I changed the saving method to an asynchronous method and had the same problem.
Then I came up with a simple solution:
//__ENABLE OR DISABLE MAIN DIALOG
void CMFCApplication1Dlg::enableMainDlg(bool enable)
{
this->EnableWindow(enable);
}
When starting the asynchronous method, I disable the main dialog.
This prevents the user from interacting with the main dialog (like starting another saving process which could result in thousands of SQL error messages if I wouldn't check if the saving process is already running...)
When the saving process is finished, I re-enable the main dialog.
Works like a charm, I hope this helps
One way to overcome your application from becoming unresponsive you need to tell the application to process messages from windows. When you are in your loop you can call
Application->ProcessMessages();
I had a similar issue with a win32 app that was waiting on a response from webservice using cpprest (Casablanca) api. My solution was to create a event and thread that does nothing but wait for the cpprest api and then release the thread once it recieves the signal:
DWORD WINAPI WaitForCasablanca(LPVOID n)
{
// Get the handler to the event for which we need to wait in
// this thread.
HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, false, "MyEvent");
if (!hEvent) { return -1; }
// Loop through and wait for an event to occur
// Wait for the Event
WaitForSingleObject(hEvent, INFINITE);
// No need to Reset the event as its become non signaled as soon as
// some thread catches the event.
CloseHandle(hEvent);
return 0;}
BOOL WINAPI DlgProc(HWND hDlg, UINT message, WPARAM,wParam, LPARAM lParam) ...
HANDLE hEvent = CreateEvent(NULL, false, false, "MyEvent");//create an event that will wait for casablanca ro authenticate
if (!hEvent) return -1;
// Create a Thread Which will wait for the events to occur
DWORD Id;
HANDLE hThrd = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)WaitForCasablanca, 0, 0, &Id);
if (!hThrd) { CloseHandle(hEvent); return -1; }
makeCasablancaRequest(...);
SetEvent(hEvent); //casablanca has finished signal the event to terminate
WaitForSingleObject(hThrd, INFINITE); //wait for thread to die
CloseHandle(hThrd);
CloseHandle(hEvent);
...}
That got rid of the "program not responding" message for me. I believe the problem is the code that is getting the data is running in a thread too- only the main program doesn't know this- so as far as the system is concerned the main program is idling. You need an event and a thread that waits for the event to tell the system the program is waiting on data. I got the code from this tutorial: How to use WIN32 Event Kernel Object