1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

How to let a user cancel a thread at any time.

Discussion in 'Win32' started by ever_thus, Feb 19, 2007.

  1. ever_thus

    ever_thus New Member

    Here's a problem I encounter very often in GUI programming and I'm not even sure how to google it.

    A task is executing. While it does so I display a dialog that tells the user what is going on. The dialog has a cancel button. Since I can't be in the message loop while executing the given task, the dialog executes in its own thread.

    The problem is, how does the task know when the user has hit the cancel button. I don't want to have keep polling an event. What's more, sometimes there is a separate error handling function (when the main function is retrying the task several times) which the function executing the task shouldn't know about.

    I'm sure there must be a simple elegant solution to such situations. If anyone can help I'd be grateful.
  2. shabbir

    shabbir Administrator Staff Member

    The normal way of doing it or more accuartely the way I do it is.

    I start a thread in the Message Loop and then return so that the Message Loop is not blocked and use the MsgWaitForSingleObject for the completion of the thread.

    Now in the body of the thread there is a check for a variable which just stops the running thread and sets the event so that the wait is over and the job is cancelled.
  3. ever_thus

    ever_thus New Member

    I'm not sure I understand. The message loop runs countless times and we don't want to start a thread in each iteration. Also what do you return from; CreateThread returns immediately.

    Could you possibly post the psuedocode?
  4. shabbir

    shabbir Administrator Staff Member

    What I meant by the message loop and return is that in the event handler of the message I create the thread and return and so that the other messages just dont get blocked.
  5. ever_thus

    ever_thus New Member

    Thanks for your reply. I didn't know about the MsgWaitForMultipleObjects API. What I've done is create a thread in the error handler, pass it an event, have the thread create a dialog and, in the main thread, poll the event regularly. In the dialog thread the thread uses MsgWaitForMUltipleObjects to process messages while polling the event. If the user cancels the dialog thread sets the event. If the operation succeeds the main thread sets the event which the dialog thread then ends the dialog and thread.
  6. shabbir

    shabbir Administrator Staff Member

    Thats the perfect way of doing it. Or at least the best I know off.

Share This Page