Recent

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

mangakissa

  • Hero Member
  • *****
  • Posts: 941
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 1.84 (32b) / FPC 3.0.4
Windows 10

marcov

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 7446
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: 2513
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: 941
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 1.84 (32b) / FPC 3.0.4
Windows 10