控制TThread的执行流程

时间:2014-08-15 11:35:21

标签: multithreading delphi

如何暂停/继续TThread我正在寻找被弃用的TThread.Suspend以及TThread.Resume的安全替代方案。

1 个答案:

答案 0 :(得分:4)

这是我最终解决的问题。暂停/恢复的安全替代方案。

     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;