Nil variable when thread comeplete

Hi there,

I have a thread for example TMyThread, and then i have this

var
  MyThread : TMyThread;

as global.

Then I have Button1 -> Onclick ->
 begin
   If MyThread = nil then
   begin
     MyThread := TMyThread.create;
     MyThread.Resume;
    end;
  end;

And my thread goes on it's happy way. Now after 5 minutes when I click on the button again, nothing happens. It seems when the Thread is finished it dosn't set the varialbe back to nil.

How can I set MyThread variable to nil once the thread is complete? (freeonterminate is set to true).

LVL 10
wildzeroAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Russell LibbyConnect With a Mentor Software Engineer, Advisory Commented:
Create a TNotify event (eg, on the form)

type
  TForm1         =  class(TForm)
     procedure   FormCreate(Sender: TObject);
  private
     // Private declarations
  protected
     // Protected declarations
     procedure   OnTerminate(Sender: TObject); // <- To handle the thread OnTerminate
  public
     // Public declarations
  end;


---
then implement it as:

procedure TForm1.OnTerminate(Sender: TObject);
begin

  MyThread:=nil;

end;

----

then bind the thread's OnTerminate event to this:

   If MyThread = nil then
   begin
     MyThread := TMyThread.create;
     MyThread.OnTerminate:=Form1.OnTerminate;
     MyThread.Resume;
    end;

---

Regards,
Russell

0
 
maradamCommented:
Freeing does not set automaticallly all the referencing variables to nil. If you are sure that the thread is terminated just set MyThread variable to nil. Buf finding out is not so easy in your case. If the thread is terminated (and then freed) you can't check Terminated property. Maybe a good idea is not to set FreeOnTerminate to true add the code below before checking MyThread = nill

if MyThread.Terminated begin
  MyThread.Free;
  MyThread:=nil;
end
if MyThread = nil ...
0
 
wildzeroAuthor Commented:
Hi Russell, that looks perfect! I should of thought of that.

Maradam - Not quite what I was after there.

Btw - make sure to check out my other thread question I just opened ;-)
0
All Courses

From novice to tech pro — start learning today.