【问题标题】:Simple multithreading Delphi简单的多线程 Delphi
【发布时间】:2015-04-09 13:12:43
【问题描述】:

我对线程还是很陌生。我想创建一个程序,在主线程创建必要的表单时测试有效的互联网连接。代码 sn-p 在构造函数的末尾停止,并出现“无法在正在运行或挂起的线程上调用 Start”错误。并且由于某种原因,主窗体在此错误后关闭

constructor TPingThread.Create(IDThread: Integer);
begin
  Self.FID:=IDThread;
  Self.FreeOnTerminate:=true;
end;

destructor TPingThread.Destroy;
begin
  EndThread(FID);
  inherited;
end;

procedure TPingThread.Execute;
var
  iTimeOuts, K: Byte;
  sWebpage: String;
begin
  inherited;
  iTimeOuts:=0;
  FIdPing:=TIdHTTP.Create(nil);
  for k:=1 to 3 do
    begin
      Try
        FIdPing.ConnectTimeout:=2000;
        sWebpage:=FIdPing.Get('http://www.google.co.za')
      Except
        On Exception do inc(iTimeOuts);
      End;
    end;
  if iTimeOuts=3 then MessageDlg('A working internetconnection is needed to reset your password',mtWarning,[mbOK],0);
  if iTimeOuts=0 then FInternetConnection:=false
  else FInternetConnection:=true;
  FreeAndNil(FIdPing);
end;

【问题讨论】:

  • 您忘记在构造函数中调用inherited
  • 并且不要在Execute中调用继承。
  • 产生不兼容类型错误
  • 继承创建(false); // 运行线程
  • @Marnu123 类型不兼容,因为您的构造函数是重载。您必须调用基本构造函数 - inherited Create(true) 来创建暂停的线程

标签: multithreading delphi


【解决方案1】:

您的代码存在一些问题:

  1. 你需要调用inherited构造函数:

    constructor TPingThread.Create(IDThread: Integer);
    begin
      inherited Create(false); // Or true to create a suspended thread
      Self.FID:=IDThread;
      ...
    
  2. 删除Execute 方法中的inherited 调用,因为这是TThread 的抽象声明。本身不是错误,但为了清楚起见应该避免。

  3. 在 Execute 方法中创建 FIdPing 后使用 try/finally。

  4. 正如@mjn 所说,无需调用EndThread(),因为TThread 会为您处理。

  5. 从线程调用 VCL MessageDlg() 不是线程安全的。您需要同步调用或使用Application.MessageBox,这是一个Delphi 包装器到Windows MessageBox。最好的解决方案是跳过对话框并将错误消息传递给主线程,主线程无论如何都需要知道这个错误。

【讨论】:

  • 我亲自删除了抽象方法的 inherited 调用(即使 IDE 生成了它),但这真的会伤害什么吗?
  • @TLama,也许我错了,但是对抽象方法的调用应该给出EAbstractError 或类似的东西。
  • @TLama,当您调用 inherited 时,编译器会检查继承的调用是否有效。
  • @LURD,如果你明确写了inherited Execute;(至少在Delphi XE3中),也不关心检查。我将继续从生成的类骨架中删除任何抽象方法的 inherited 调用。
  • @TLama,如果方法是函数,Result := inherited 会导致异常。我也总是扔掉抽象方法。
猜你喜欢
  • 2011-03-27
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
  • 2014-01-29
相关资源
最近更新 更多