F
F
Fenix9572016-11-08 03:04:47
Delphi
Fenix957, 2016-11-08 03:04:47

How to create a component in a thread and leave it in delphi?

In general, it was necessary to create a component in a thread but not destroy this component when the thread ends. can anyone tell me how the component is created now

TMyThread = class(TThread)
    private
    { Private declarations }
  protected
    procedure Execute; override;
  end;
var
  Form6: TForm6;
   MyThread: TMyThread;
    Memo: TMemo;
implementation

{$R *.dfm}

{ TMyThread }

procedure TMyThread.Execute;
begin
 Memo:=TMemo.Create(Form6);
  Memo.Parent:=Form6;
  Memo.Left:=50;
  Memo.Top:=50;
  Memo.Width:=250;
  Memo.Height:=100;
  Memo.Text:='Мама я родился!';
  ///MyThread.Suspend; приоставление потока но тогда работать с компонетом работать не возможно а если не ставить это то компонент уничтожается по завершении потока 
end;

procedure TForm6.btn1Click(Sender: TObject);
begin
MyThread:=TMyThread.Create(False);
//Параметр False запускает поток сразу после создания, True - запуск впоследствии , методом Resume
//Далее можно указать параметры потока, например приоритет:
  MyThread.Priority:=tpNormal;
end;

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mercury13, 2016-11-08
@Fenix957

It is possible, only synchronously. Use TThread.Synchronize. The code is written from the sheet, I'm not sure if it's valid.

procedure TMyThread.SyncCreateMemo;
begin
 Memo:=TMemo.Create(Form6);
  Memo.Parent:=Form6;
  Memo.Left:=50;
  Memo.Top:=50;
  Memo.Width:=250;
  Memo.Height:=100;
  Memo.Text:='Мама я родился!';
end;

procedure TMyThread.Execute;
begin
  Synchronize(SyncCreateMemo);
end;

The second method, more complex and dangerous, is PostMessage. Here, the flow will not experience any delays. But be careful - the form will create a component at any time and you can not fill it right away.
procedure TForm6.WmCreateMemo; // message WM_CREATEMEMO = WM_USER + 1
begin
 Memo:=TMemo.Create(Form6);
  Memo.Parent:=Self;
  Memo.Left:=50;
  Memo.Top:=50;
  Memo.Width:=250;
  Memo.Height:=100;
  Memo.Text:='Мама я родился!';
end;

procedure TMyThread.Execute;
begin
  PostMessage(Form6.Handle, WM_CREATEMEMO, 0, 0);
end;

You can also fill in our editor using PostMessage, but here, too, be careful: the messages will be executed in order, but no one knows whether before the end of the stream or not. It also happens that two messages have gone into the queue, but have not yet been processed. In general, be extremely careful with object lifetime.

R
Ravil Zaripov, 2016-11-08
@RZaripov

you cannot create visual components in an additional thread

D
DeathGun, 2016-12-02
@DeathGun

Everything is possible, through the thread constructor we pass a pointer to the component in the twincontrol format. We use the synchronize function and not any glitches!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question