I'm having a little trouble shutting down a thread that might or might not be executing when the program closes. The thread, actually there are two of them, is started in an OnTimer event, and in OnDestroy I stop the timers then I want to close the threads.
The thread code itself is pretty simple and this is what I have now.
Still, I get an access violation error, and when I use the WaitFor function I get lots of odd errors, such as invalid handle.
// Constructor
constructor TDaqThread.Create(OnTerminate:TNotifyEvent);
begin
inherited Create(true);
Self.OnTerminate:=OnTerminate; // Defines the onTerminate event handler
FreeOnTerminate:=true; // Thread frees itself when it terminates
Resume; // Start the thread
end;
// The thread executes a single procedure
procedure TDaqThread.Execute;
begin
try
MainForm.DoUpdateDaq;
except
on E:Exception do
begin
// Handle the error.
end
end;
end;
// Here is how I create/start the thread. When it is done I run the
// EndUpdateDaq procedure.
DaqThread:=TDaqThread.Create(EndUpdateDaq)
// At the beginning of the EndUpdateDaq procedure...
procedure TMainForm.EndUpdateDaq(Sender:TObject);
begin
try
// Has the Daq thread been terminated?
if DaqThread<>nil then
if DaqThread.Terminated then
Exit;
// More stuff...
end;
Procedure TMainForm.OnDestroy(Sender:TObject);
begin
MonitorTimer.Enabled:=false;
if DaqThread <> nil then
if not DaqThread.Terminated then
begin
DaqThread.OnTerminate:=nil;
DaqThread.Terminate; // Stop the Daq thread
// DaqThread.WaitFor; // Wait for it to terminate
end;
// more stuff...
end;