代码之家  ›  专栏  ›  技术社区  ›  Stelios Antoniou

在数字运算应用程序中从后台线程向主线程发送消息

  •  0
  • Stelios Antoniou  · 技术社区  · 3 年前

    我在Delphi中有一个数字运算应用程序,它使用一个或多个后台线程来处理数字数据。这些后台线程同时运行多个并行进程。从这些线程中,我使用WM_COPYDATA消息将信息传递给主线程,以便向用户提供反馈。

    在我的电脑中,我有英特尔酷睿i7-10750H CPU处理器(6个物理内核和12个线程),我的RAM是32GB。 当我同时运行一个或两个分析(CPU使用率50-80%,内存消耗1-2GB)时,消息由主线程正确传递和处理,即我在主窗体的GUI中获得反馈。然而,当我将系统推向极限时(在具有6个物理核的PC中进行6个并行分析,CPU使用率>90%,内存消耗>2.5GB),消息通常不会传递到主线程,并且我在GUI中没有得到任何反馈(不知何故,它们似乎丢失了)。但是,后台线程运行正确,并且在分析结束时,它们提供了正确的结果。

    问题出在哪里,消息没有得到处理?我能做点什么来解决这个问题吗? 非常感谢。

    数据通过以下记录传递:

    type
      TCommunicationMsgRecord = record
        AnalysisID: integer;
        UpdateType: integer;
        MessageStr: String[255];
        prbProgress: integer;
        valX,valY: real;
      end;
    

    后台线程中的代码如下:

    procedure TExecution.SetMainFormMemoProcess(const str: string);
    var
      CommunicationMsgRecord: TCommunicationMsgRecord;
      copyDataStruct : TCopyDataStruct;
    begin
          CommunicationMsgRecord.AnalysisID := Self.ExecutionID;
          CommunicationMsgRecord.UpdateType := 0;
          CommunicationMsgRecord.MessageStr := StrLeft(str,255);
          CommunicationMsgRecord.prbProgress := 0;
          CommunicationMsgRecord.valX := 0;
          CommunicationMsgRecord.valY := 0;
          //------------------------------------------------------
          copyDataStruct.dwData := 0;
          copyDataStruct.cbData := SizeOf(CommunicationMsgRecord);
          copyDataStruct.lpData := @CommunicationMsgRecord;
          SendMessage(MainForm.handle, WM_COPYDATA, Integer(hInstance), Integer(@copyDataStruct));
    end;
    

    主线程中的代码如下:

    type
      TMainForm = class(TForm)
      private
        procedure WMCopyData( var Msg : TWMCopyData ); message WM_COPYDATA;
    
    implementation
    procedure TMainForm.WMCopyData(var Msg: TWMCopyData);
    var
      CommunicationMsgRecord : TCommunicationMsgRecord;
    begin
        try
            CommunicationMsgRecord:= TCommunicationMsgRecord(Msg.CopyDataStruct.lpData^);
            case CommunicationMsgRecord.UpdateType of
               0: MainForm.memoProcess.Lines.Add(CommunicationMsgRecord.MessageStr);
               1: MainForm.Statusbar.Panels[0].Text := CommunicationMsgRecord.MessageStr;
               //other options (e.g. plotting) that receive the data from CommunicationMsgRecord
               //....
            end;
        except
              on E: EAccessViolation do
               begin
                  ShowMessage('Access Violation');
               end;
               on E: Exception do //this will catch all your other exceptions
               begin
                  ShowMessage('Other Error');
               end;
          end;
    end;
    
    0 回复  |  直到 3 年前
        1
  •  4
  •   Remy Lebeau    3 年前

    首先,使用 WM_COPYDATA 在这种情况下太过分了。它用于跨流程边界序列化数据,而您并没有这样做。由于您在同一过程中向窗口发送数据,因此只需在自定义消息中直接发送数据指针即可。

    此外,不要使用 Integer() 类型强制转换,只能在32位中使用。如果你决定编译64位应用程序(即访问更多内存),代码如下 将 失败的第4个参数 SendMessage() 是 LPARAM ,而不是 Integer 。 LPARAM 是32位或64位整数,具体取决于CPU架构。使用正确的类型。

    type
      PCommunicationMsgRecord = ^TCommunicationMsgRecord;
      TCommunicationMsgRecord = record
        AnalysisID: integer;
        UpdateType: integer;
        MessageStr: String[255];
        prbProgress: integer;
        valX,valY: real;
      end;
    
    const
      WM_MY_DATA_MSG = WM_APP + 100;
    
    procedure TExecution.SetMainFormMemoProcess(const str: string);
    var
      CommunicationMsgRecord: TCommunicationMsgRecord;
    begin
      CommunicationMsgRecord.AnalysisID := Self.ExecutionID;
      CommunicationMsgRecord.UpdateType := 0;
      CommunicationMsgRecord.MessageStr := StrLeft(str,255);
      CommunicationMsgRecord.prbProgress := 0;
      CommunicationMsgRecord.valX := 0;
      CommunicationMsgRecord.valY := 0;
    
      SendMessage(MainForm.Handle, WM_MY_DATA_MSG, 0, LPARAM(@CommunicationMsgRecord));
    end;
    
    ...
    
    type
      TMainForm = class(TForm)
      private
        procedure WMMyDataMsg( var Msg : TMessage ); message WM_MY_DATA_MSG;
        ...
      end;
    
    procedure TMainForm.WMMyDataMsg(var Msg: TMessage);
    var
      CommunicationMsgRecord : PCommunicationMsgRecord;
    begin
      try
        CommunicationMsgRecord := PCommunicationMsgRecord(Msg.LParam);
        case CommunicationMsgRecord.UpdateType of
          0: MainForm.MemoProcess.Lines.Add(CommunicationMsgRecord.MessageStr);
          1: MainForm.StatusBar.Panels[0].Text := CommunicationMsgRecord.MessageStr;
          //....
        end;
      except
        ...
      end;
    end;
    

    第二,使用 MainForm.Handle 你现在的处境并不安全。VCL 可以 (有时确实如此) HWND s在运行时是动态的。如果你碰巧读到 Handle 属性,同时VCL正在重新创建该属性的 HWND ,非常糟糕的事情可能会发生。您应该使用单独的 HWND 保证是持久的,例如 TApplication.Handle (使用 TApplication.HookMainWindow() 接收其消息),或者更好的结果 AllocateHWnd() 。

    话虽如此,如果您向主线程发送了大量消息,那么您可能正在填充主线程的消息队列。队列一次只能容纳这么多消息(IIRC,限制为10000),但您显示的代码没有对 SendMessage() 打电话,例如:。

    procedure TExecution.SetMainFormMemoProcess(const str: string);
    var
      ...
      ErrCode: DWORD;
    begin
      ...
      if SendMessage(...) = 0 then
      begin
        ErrCode := GetLastError();
        if ErrCode = ERROR_NOT_ENOUGH_QUOTA then
          // the message queue is full ...
      end;
    end;
    

    此外,请注意 SendMessage() 是同步的,在消息处理程序处理消息之前它不会返回,这意味着您的工作线程将相互同步,从而减慢它们的处理速度,因为如果一个线程试图同时发送数据,则必须等待另一个线程。为了避免这种情况,请使用 PostMessage() 相反(并动态分配发布的数据),以便您的线程可以全速运行,例如:

    procedure TExecution.SetMainFormMemoProcess(const str: string);
    var
      CommunicationMsgRecord: PCommunicationMsgRecord;
    begin
      New(CommunicationMsgRecord);
      CommunicationMsgRecord.AnalysisID := Self.ExecutionID;
      CommunicationMsgRecord.UpdateType := 0;
      CommunicationMsgRecord.MessageStr := StrLeft(str,255);
      CommunicationMsgRecord.prbProgress := 0;
      CommunicationMsgRecord.valX := 0;
      CommunicationMsgRecord.valY := 0;
    
      if not PostMessage(MainForm.Handle, WM_MY_DATA_MSG, 0, LPARAM(CommunicationMsgRecord)) then
      begin
        Dispose(CommunicationMsgRecord);
        ...
      end;
    end;
    
    ...
    
    procedure TMainForm.WMMyDataMsg(var Msg: TMessage);
    var
      CommunicationMsgRecord : PCommunicationMsgRecord;
    begin
      try
        CommunicationMsgRecord := PCommunicationMsgRecord(Msg.LParam);
        try
          ...
        finally
          Dispose(CommunicationMsgRecord);
        end;
      except
        ...
      end;
    end;
    

    但是,要小心,因为这可能会更快地填满主线程的消息队列,因此您应该考虑将数据结果存储在线程安全内存的其他位置,然后让主线程定期(例如在计时器中)显示最新结果,而不是在每次数据更新时显示。