Use WaitForMultipleObjects() with an array of two events instead of WaitForSingleObject() . Add a reset message to the stream class and pass it after you set Terminated to True . Check the return value, which of the two events has been signaled, and act accordingly.
Edit:
Some minimal Delphi 2009 code to demonstrate the idea. You must add SyncObjs to the list of units used and add
fTerminateEvent: TEvent;
to the private section of your thread class.
constructor TTestThread.Create; begin inherited Create(TRUE); fTerminateEvent := TEvent.Create(nil, True, False, ''); // ... Resume; end; destructor TTestThread.Destroy; begin fTerminateEvent.SetEvent; Terminate; // not necessary if you don't check Terminated in your code WaitFor; fTerminateEvent.Free; inherited; end; procedure TTestThread.Execute; var Handles: array[0..1] of THandle; begin Handles[0] := ...; // your event handle goes here Handles[1] := fTerminateEvent.Handle; while not Terminated do begin if WaitForMultipleObjects(2, @Handles[0], False, INFINITE) <> WAIT_OBJECT_0 then break; // ... end; end;
You only need to add the code in your question to it. Just trying to free an instance of a thread will do whatever it takes to unlock the thread (if necessary).
mghie source share