multithreading - 简单的多线程Delphi

标签 multithreading delphi

我对线程还很陌生。我想创建一个程序,在主线程创建必要的表单时测试有效的互联网连接。代码片段在构造函数末尾停止,并出现“无法在正在运行或挂起的线程上调用 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;

最佳答案

您的代码存在一些问题:

  1. 您需要调用继承构造函数:

    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(Windows MessageBox 的 Delphi 包装器)。最好的解决方案是跳过对话框并将错误消息传递给主线程,无论如何主线程都需要知道此错误。

关于multithreading - 简单的多线程Delphi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29539493/

相关文章:

Java Swing 重绘延迟

java - 锁定问题: needs some brainstorming suggestions

delphi - 命令历史记录单元的意外行为

delphi - 德尔福·安西丝特斯(Delphi Ansistrings)

delphi - 如何设计可变数据大小的 FIFO 队列?

java - 从 ConcurrentLinkedDeque 的特定位置获取元素

java - Concurrentlinkedqueue在多线程环境下未命中添加数据

delphi - Delphi 32个组件模仿“患者旅程演示器”

delphi - Windows 7 上的视觉主题和 Delphi 7

c++ - 如何使用多线程读取文件?