tags:

views:

30

answers:

2

I'm calling a subroutine form the WndProc function in a windows app. WndProc was called from the message processing loop when a button was pushed. The subroutine takes a fair amount of time to run so it sends periodic messages using SendMessage(WM_USER). These messages should cause screen updates. Unfortunately, the updates are all held until the subroutine returns; at that time all the messages are processed and the screen updated. The handler for the message is in WndProc; it invalidates the window which should cause a paint message to be generated.

Do I need to run the subroutine as a separate thread?

A: 

The best would be to use a separate thread. But you could run the message loop in your handler function too:

HWND hwnd; 
BOOL fDone; 
MSG msg; 

// Begin the operation and continue until it is complete 
// or until the user clicks the mouse or presses a key. 

fDone = FALSE; 
while (!fDone) 
{ 
    fDone = DoLengthyOperation(); // application-defined function 

    // Remove any messages that may be in the queue. If the 
    // queue contains any mouse or keyboard 
    // messages, end the operation. 

    while (PeekMessage(&msg, hwnd,  0, 0, PM_REMOVE)) 
    { 
        switch(msg.message) 
        { 
            case WM_LBUTTONDOWN: 
            case WM_RBUTTONDOWN: 
            case WM_KEYDOWN: 
                // 
                // Perform any required cleanup. 
                // 
                fDone = TRUE; 
        } 
    } 
} 
Stefan
@Stefan: How is the code in the while loop going to be executed if the thread is off in the DoLengthyOperation function?
Mike D
DoLenghtyOperation() doesn't execute everything, only a part, then returns and continues with the lengthy task the next time it is called.
Stefan
A: 

If you want your UI to remain responsive while the subroutine runs, you either have to pump messages within the subroutine (which can itself get you into re-entrancy nasties), or move the subroutine out to a thread. The preferred way to do this is with a Worker thread.

There's an intro to worker threads on my website here. When the thread finishes its work, you can post a registered message back to your main window. Worker threads are pretty easy.

Anticipating your next question about cancelling a lengthy operation, there's a discussion of the options available to you for doing that on my site here. Warning, some of them are very silly, but I do try to be complete :-)

Bob Moore