TOpenDialog and Multi Thread

193 Views Asked by At

This is very curious behaviour of simple Embarcadero Delphi (v. 11.3) application... When same thread is launched 2 or 3 times (see code below) with 2 or 3 times click on Button1, an TOpenDialog window (click on Button2 AFTER last instance of thread ended) freezes the application. No error message is rised and it is necessary to close app from Win task manager (Ctrl+Alt+Del).

{MAIN UNIT}
procedure TForm1.Button1Click(Sender: TObject);
Begin
  MyThread:= TMyThread.Create(false);
End;
    
procedure TForm1.Button2Click(Sender: TObject);
Begin
  OpenDialog1.Execute;
End;
  
{THREAD UNIT}
procedure TMyThread.Execute;
Begin
  Sleep(2000);
  Synchronize(UpdateMainForm);
End;
    
procedure TMyThread.UpdateMainForm;
Begin
  Form1.Label1.Text:= 'Now thread ended!';
  EndMyThread;
End;

procedure TMyThread.EndMyThread;
Begin
  FreeOnTerminate:= true;
End;
1

There are 1 best solutions below

4
mjn On

FreeOnTerminate := True is executed in the context of the main (VCL) thread in your code.

The line

FreeOnTerminate := True;

should be in the TMyThread.Create constructor instead.


https://docwiki.embarcadero.com/Libraries/Sydney/en/System.Classes.TThread.FreeOnTerminate