A strange problem in threads, the application does not exit

OK. I am writing a Zoom component, and I wanted it to capture the screen in a secondary stream. You can pretend that I just want to get TThread in an empty component. I did not write any codes in the stream, so this is just a simple useless stream. I wrote this code: Thrd := TCaptureThread.Create(False);in the main class of the component. Then I wrote Thrd.Freein the destruction code of the main class. Now, when I close the entire application, although it destroys everything, the process does not end completely. Windows Task Manager shows that the number of threads is 1, but the process remains. If I comment on the thread creation line, everything will be OK, and the application will exit quickly. What will I do with this ?: (

Thanks in advance

+2
source share
3 answers

When you call Thrd.Free, the following code is run from TThread.Destroy:

Terminate;
if FCreateSuspended then
  Resume;
WaitFor;

A call Freein the stream will thus interrupt the stream synchronously.

I guess the call WaitFornever returns. Perhaps it TCaptureThread.Executedoes not check Terminatedand does not exit. Perhaps TCaptureThreadwaiting in the main thread, and therefore waiting in the dead ends of the thread.

It is very difficult to do anything other than guessing based on your question, but I would like to check if your code passed after the call WaitForupon destruction Thrd. Turn on Debug DCU, set a breakpoint on the call, WaitForand see for yourself.

+6
source

It could be so much ... From a method of Executeyour thread that never gets stuck.

, , , - Delphi. , , , . , , Thread. , , . , , , .

0

Write your stream along this path:

type
  TCaptureThread = class(TThread)
  private
    //
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: False);
  end;

implementation

constructor TCaptureThread.Create(CreateSuspended: Boolean);
begin
  inherited Create(CreateSuspended);
  // Set FreeOnTerminate to True
  FreeOnTerminate := True;
end;

procedure TCaptureThread.Execute;
begin
  // Write the Execute method here...
  // And don't forget to synchronise with the form
end;

end.

Create your stream in the form

Thrd := TCaptureThread.Create(False);

Run it

Thrd.Execute;

And end your thread

Thrd.Terminate;

I have been using threads along this path for a while and I have never had a problem.

-2
source

All Articles