Recent

Author Topic: Thread in scanner will not terminated  (Read 9785 times)

mangakissa

  • Hero Member
  • *****
  • Posts: 1131
Thread in scanner will not terminated
« on: December 17, 2014, 12:30:10 pm »
I've created an application for Symbol MC9190 with uscanner.pas. This object (declared as scanner := TStanner) runs in another thread. When I start a form, TScanner object will be started. After closing the form I use this procedure:
Code: [Select]
  {$IFDEF LCLWinCE}
    if scanner <> nil then
      scanner.Terminate;
  {$ENDIF LCLWinCE}
But I still can use the scanner on the terminal. When I open the form again, the application comes with this message:
Quote
Error Scanning
Code = 25
It wants to start the thread but couldn't do it, because it already running.

How can I stop the thread and started again by opening a form?
Lazarus 2.06 (64b) / FPC 3.0.4 / Windows 10
stucked on Delphi 10.3.1

marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 11382
  • FPC developer.
Re: Thread in scanner will not terminated
« Reply #1 on: December 17, 2014, 12:46:03 pm »
Maybe you are simply too fast shutting down after Terminate; Terminate tells thread to terminate, but the thread must actually terminate. (IOW come past the WHILE not terminated clause in the .execute)

You can wait for using .waitfor:
Code: [Select]
if (assigned(scanner) then
   begin
      scanner.terminate;  // signal request for termination
      scanner.waitfor;      // wait for termination
      scanner.free;  // deallocate
   end;


engkin

  • Hero Member
  • *****
  • Posts: 3112
Re: Thread in scanner will not terminated
« Reply #2 on: December 17, 2014, 02:47:14 pm »
Free does call both Terminate and WaitFor.

TScanner.Create is setting FreeOnTerminate to true, so change your code to:
Code: [Select]
  {$IFDEF LCLWinCE}
    if scanner <> nil then
    begin
      scanner.Terminate;
      scanner.WaitFor;
    end;
  {$ENDIF LCLWinCE}

Or reuse the scanner thread by assigning nil to OnScan and OnError when you close a form, and re-assign them when you open a new form. Terminate the scanner thread only when the application closes.

mangakissa

  • Hero Member
  • *****
  • Posts: 1131
Re: Thread in scanner will not terminated
« Reply #3 on: December 17, 2014, 04:06:14 pm »
Thanks, Marcov and engkin.

I noticed it takes a lot of time to actually terminate the thread. If the customer wants I shall open the thread during the application. I'm glad it's working now.
Lazarus 2.06 (64b) / FPC 3.0.4 / Windows 10
stucked on Delphi 10.3.1

 

TinyPortal © 2005-2018