二小姐的茶会吧 关注:40贴子:1,378
  • 19回复贴,共1

从度娘处得知此吧,特前来请教吧主一个关闭并行计算的问题....

只看楼主收藏回复

很简单,就是关于如何在主线程终止TTask....我在TTask里面写了一个while 死循环,不断读取某些数据, 当系统关闭前应该发个信号过来,让其退出 ...
传统的Thread,里面可以用peekmessage, 这个TTask好像都隐藏了这些东西...
@二小姐


IP属地:广东1楼2015-09-23 19:05回复
    这个随意都行吧,比如用接口自带的一个方法
    var
    Task: ITask;
    procedure TForm1.Button1Click(Sender: TObject);
    begin
    Task := TTask.Create(
    procedure()
    begin
    while True do
    begin
    try
    Task.CheckCanceled; // 当调用Cancel后该过程会触发一个异常,只须捕捉该异常进行处理
    except
    Break;
    end;
    Edit1.Text := DateTimeToStr(Now);
    end;
    end);
    Task.Start;
    end;
    procedure TForm1.Button2Click(Sender: TObject);
    begin
    Task.Cancel;
    end;


    IP属地:广东2楼2015-09-23 19:42
    收起回复
      或者用什么其他设施也一样:
      const
      FormClosing = -1;
      procedure TForm1.Button1Click(Sender: TObject);
      var
      Task: ITask;
      begin
      Task := TTask.Create(
      procedure()
      begin
      while True do
      begin
      if Self.Tag = FormClosing then
      Break;
      Edit1.Text := DateTimeToStr(Now);
      end;
      end);
      Task.Start;
      end;
      procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
      begin
      Self.Tag := FormClosing;
      end;


      IP属地:广东3楼2015-09-23 19:53
      收起回复
        接着上楼的加点你后来提到的:
        type
        TForm1 = class(TForm)
        Button1: TButton;
        Edit1: TEdit;
        Button2: TButton;
        procedure Button1Click(Sender: TObject);
        procedure FormClose(Sender: TObject; var Action: TCloseAction);
        procedure Button2Click(Sender: TObject)
        publi
        procedure DoSomething;
        end;
        var
        Form1: TForm1;
        implementation
        uses System.Threading;
        {$R *.dfm}
        const
        FormClosing = 1;
        procedure TForm1.Button1Click(Sender: TObject);
        var
        Task: ITask;
        begin
        ShowMessage(TThread.Current.ThreadID.ToString);
        Task := TTask.Create(
        procedure()
        begin
        try
        while True do
        begin
        if Self.Tag = FormClosing then
        Break;
        Edit1.Text := TThread.Current.ThreadID.ToString;
        end;
        finally
        TThread.Synchronize(nil, procedure begin Form1.DoSomething end);
        end;
        end);
        Task.Start;
        end;
        procedure TForm1.Button2Click(Sender: TObject);
        begin
        Self.Tag := FormClosing;
        end;
        procedure TForm1.DoSomething;
        begin
        ShowMessage(TThread.Current.ThreadID.ToString);
        end;


        IP属地:广东4楼2015-09-23 21:03
        收起回复