We help IT Professionals succeed at work.

Nil variable when thread comeplete

wildzero
wildzero asked
on
Medium Priority
312 Views
Last Modified: 2010-04-05
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).

Comment
Watch Question

Software Engineer, Advisory
CERTIFIED EXPERT
Top Expert 2005
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

Commented:
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 ...

Author

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 ;-)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.