I’ve got an app working semi-background stuff in the GUI thread. Another thread won’t work and a timer won’t work. But I want the app to be responsive while I’m going my ‘background’ work.
I cound use application.doevents – but that gives me 3 bad choices:
- loop with no sleeps – end peg an entire CPU (my task waits on stuff besides calcs & I/O so this matters)
- loop with a sleep – then the app slows down
- Try to make a ‘smart sleep’ loop that speeds up when lots of messages happen (check for messages in messagefilter function)
In the good ole’ days in sdk I can do this:
while(PeekMessage(&msg,0,0,0,PM_REMOVE) && still_working)
{
TranslateMessage( &msg );
DispatchMessage(&msg);
// do a bit of my background work with each message here, quit the loop when done.
}
Wnd have it be a bit better than DoEvents as it will process multiple messages in a row, but I still have to use ‘smart sleep’ to save cpu – I’d like to avoid that.
Also is there a way to do a primary message loop?
MSG msg;
while( GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
Is there a proper .NET equivalent, or do I just have to p/invoke the sdk stuff?
Thanks!
EDIT Winforms. For all you answer-ers wondering why I can’t use application.run, or threads, what I want to do is handled the OnUnhandledException event, then leave my app open for a while while some winforms stuff closes it down gracefully and tells my watchdog program to restart the app. after allowing the user to finish a critical process, too. Yes, I know people thing that a program getting OnUnhandledException deserves to die (obviously MS), there are ‘dangerous’ things that could happen; none of them are as dangerous, however, as the wrath of my users.
Edit #2 – Looking for vb.net sourcecode exact translations of the above two functions.
Maybe somebody who’s good with p/invoke and declares could score a quick bounty 😉
If you are determined to write your own message loop you can.
Application.Runis closed-source so you don’t know what it’s doing besidesGetMessage,TranslateMessageandDispatchMessage, so you’d better at least callDoEventsinstead. SinceDoEventsonly processes pending messages and doesn’t wait, you can callWaitMessageto yield the CPU until there are new messages to process.This doesn’t end-peg the CPU, but then it doesn’t do any background work either.
You haven’t said what your background work is exactly, but if it’s stuff which completes asynchronously you should replace
WaitMessagewithMsgWaitForMultipleObjectsEx– although you’ll need to get the Win32 handles of the objects you are waiting on.