Whilst this can be made safe, you are playing with fire. You run the risk of re-entrancy. You have to make sure that the user cannot press the button again. I trust you have disabled it whilst the search is running. You must make sure that it is disabled before you first call ProcessMessages
.
My advice would always be to avoid using ProcessMessages
. Better would be to start the thread and arrange for it to notify the main thread when it is done. Of course, you still need to disable the button whilst the thread is running.
However, if you really must use ProcessMessages
don't do it with a busy loop like this. There's not much point using an entire processor to wait for a long running search operation to complete. Use a more intelligent blocking loop like this:
while MsgWaitForMultipleObjects(1, Thread.Handle, False,
INFINITE, QS_ALLEVENTS)=WAIT_OBJECT_0+1 do
Application.ProcessMessages;
The MsgWaitForMultipleObjects
function will block until either:
- A message is placed on the queue, or
- The thread is signaled. The thread is signaled when it is complete.
The loop terminates when the thread is signaled, but also processes any queued messages.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…