Doubt - Creation and completion of Threads in Delphi

Asked

Viewed 467 times

1

Good morning,

I am creating a chat system in Delphi, and I am using thread to render the message history without the application blocking. Before several researches, I found one thing here, another there and I adapted my need, however, I have no idea if I finished and cleaned the same from memory, and I need to make that when finishing the execution the same end completely, because this chat system will be integrated into another system, and I am trying my best to avoid an exaggerated consumption.

Here’s the test code I’m using - first time using threads, I don’t even know if I’m using it correctly:

TThreadRenderMsgs = class(TThread)
private
{ Private declarations }
   idPrivForm : Integer;
   procedure atualizaPanel;
protected
{ Protected declarations }
   procedure Execute; override;
public
{ Public declarations }
   constructor Create (const CreateSuspended : Boolean);
end;

constructor TThreadRenderMsgs.Create(const CreateSuspended: Boolean);
begin
   Self.FreeOnTerminate  := True;
   inherited Create(CreateSuspended);
end;

procedure TThreadRenderMsgs.atualizaPanel;
var
   mensagem : String;
begin
   mensagem := 'Teste';
 DM_SocketCliente.formClientPrivMsg[idPrivForm].chrChat.Browser.MainFrame.ExecuteJavaScript('addSendMessage(''' + mensagem + ''')', 'about:blank', 0);
end;

procedure TThreadRenderMsgs.Execute;
var
   i : Integer;
begin
   for i := 0 to 20 do
   begin
     if Terminated then
       Break;
     Synchronize(Self.atualizaPanel);
     Sleep(1000);
   end;
   Terminate;
end;

procedure TfrmClientePrivMsg.Button1Click(Sender: TObject);
var
   threadRenderMsgs : TThreadRenderMsgs;
begin
   threadRenderMsgs := TThreadRenderMsgs.Create(True);
   threadRenderMsgs.Start;
   threadRenderMsgs.idPrivForm := idMyPrivForm;
end;

1 answer

2


Some notes:

  • You should pass the form in Create of the thread instead of 'plunge' the id. On top of that you do . Start(); before you give it the idPrivForm. With some bad luck, you have errors in the thread, if it passes Execute before you give it the idPrivForm.

  • I think you also have to check if the thread is still running when you close the program. Maybe you should use a Tevent instead of Sleep

  • If this is really all you want to do, you can also use Ttask and save a lot of code

(This thread ends alone after 20s, it’s supposed to?)

  • 2

    thanks, I did some research and I realized that Ttask already met my needs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.