Link to home
Start Free TrialLog in
Avatar of tadzio_blah
tadzio_blah

asked on

Threads and application termination

Hi

I have an app in which a thread is called every 5mins:

  TFTPTh = class(TThread)
  private
  protected
    procedure Execute; override;
  end;

  WatekFTP : TFTPTh;

and somewhere in the proggy there is

          WatekFTP := TFTPTh.Create(False);
            repeat
              sleep(50);
              Application.ProcessMessages;
            until WatekFTP.Terminated;
          WatekFTP.Free;

this works fine.

but if i do an application.terminate while the thread is running i get a runtime error

tried to check if the thread exists and if it did it was ok but if it didn't then the runtime error came up

what is the best way to control threads to get rid of this problem ??
Avatar of LMuadDIb
LMuadDIb
Flag of United States of America image

First off, you wouldnt need the Application.ProcessMessages in your repeat, sense it in the thread
Second if your going to "free" the object like that surround it with a try finally block

          WatekFTP := TFTPTh.Create(False);
          try
            repeat
              sleep(50);
              Application.ProcessMessages;
            until WatekFTP.Terminated;
          finally
            WatekFTP.Free;
          end;

how are you terminating the thread?

ahh, I see...
your timer is for checking for when the thread is complete, and not in the thread itself.... sorry

set:
FreeOnTerminate := True;
but you must also make sure your not in a infinite loop in your thread
make sure its getting terminated, enclose your thread process in a try finally blocks

sleep(50) is pretty fast, if your gonna use that sleep/processmessages then you might want to use something slower
ASKER CERTIFIED SOLUTION
Avatar of TheRealLoki
TheRealLoki
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tadzio_blah
tadzio_blah

ASKER

the thread is used to upload some data to my ftp
i've allready tried all of the above and the runtime error still comes up :/

the thing is if a user clicks on close app (executes the application.terminate in the main thread) while the WatekFTP thread is running then the user gets the error

and if i put:
if not(WatekFTP.Terminated) then
repeat
sleep(500);
until WatekFTP.Terminated;

in the closing procedure and the thread is allready freed the error comes up (but if i won't do the WatekFTP.Free then it's ok but in a short time the app will use a great deal of memory)
ok, what is your thread doing in the main vcl?
does it, for instance, update a progress bar?
It sounds to me, like your form has begun to close, and the thread is trying to do something with the form, and getting an access violation.
are you doing "synchronize()" for every call to the main vcl the thread does?
are you checking "if terminated" in the thread?