TThread execution control

How can I pause / continue TThread

I'm looking for a safe alternative to the deprecated ones TThread.Suspend

as well TThread.Resume

.

+3


source to share


1 answer


Here is the solution I came across. Safe alternative to Suspend / Resume.



     type
      TMyThread = class(TThread)
      private
        FHandles: array[0..1] of THandle;
      protected
        procedure Execute; override;
      public
        constructor Create;
        destructor Destroy; override;
        procedure Pause;
        procedure UnPause;
        procedure Stop;
      end;

      constructor TMyThread.Create;
      begin
        inherited Create(False);
        FHandles[0] := CreateEvent(nil, False, False, nil);
        FHandles[1] := CreateEvent(nil, True, True, nil);
        FreeOnTerminate := True;
      end;

      destructor TMyThread.Destroy;
      begin
        CloseHandle(FHandles[1]);
        CloseHandle(FHandles[0]);
        inherited Destroy;
      end;

      procedure TMyThread.Execute;
      begin
        while not Terminated do
        begin
          case WaitForMultipleObjects(2, @FHandles[0], False, INFINITE) of
            WAIT_FAILED:
              RaiseLastOsError;
            WAIT_OBJECT_0:
              Terminate;
            WAIT_OBJECT_0 + 1:
              begin

              end;
          end;
        end;

      end;

      procedure TMyThread.Pause;
      begin
        ResetEvent(FHandles[1]);
      end;

      procedure TMyThread.UnPause;
      begin
        SetEvent(FHandles[1]);
      end;

      procedure TMyThread.Stop;
      begin
        SetEvent(FHandles[0]);
      end;

      

+4


source







All Articles