Which is the correct way to wait for a Thread.finalization and keep my application responsive

前端 未结 5 1323
陌清茗
陌清茗 2021-02-07 18:02

Actually i am using this code and works ok, but i \'am wondering if is the correct way.

  while WaitForSingleObject(MyThread.Handle, 0) = WAIT_TIMEOUT do
    App         


        
5条回答
  •  情歌与酒
    2021-02-07 18:41

    While it looks okay, like jachguate I would use a bigger time-out value than 0 too. If you use WaitForSingleObject(MyThread.Handle, 100) then the main thread will wait a bit longer, thus eating up less CPU cycles.
    A better solution would be the use of messages, though. Your application starts the thread and then puts all controls in disabled mode. The thread then executes and when it's finished, use SendMessage or PostMessage to the main window to notify it that the thread is done again. Then your application will just enable every control (and whatever else) again. This has as advantage that you keep the "natural" messageloop for the application alive, instead of running your own messageloop with this solution.
    Unfortunately, the message-method has one drawback: if the thread crashes then no message will be sent back, so a backup plan would be practical. For example, by adding a timer control to your mainform which checks every second if the thread is still alive. If not, it too would just activate the form again, disabling itself again.

提交回复
热议问题