为每个线程分配一个面板-Delphi [英] Assigning a Panel to each thread- Delphi

查看:94
本文介绍了为每个线程分配一个面板-Delphi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个同时运行多个线程的程序.每个线程都连接一个数据库,并将数据从一个表传输到另一个表.现在,我想为MainForm中的每个线程分配一个面板,以便在成功重试后将面板的颜色更改为绿色(如果连接成功)或红色(如果断开).

I have a program running several threads simultaneously. Each thread connects a database and transfers data from one table to another. Now I want to assign a panel to each thread in the MainForm so I can change color of the Panel to green if the connection is successful or to red if it's broken after a number of retries.

那么我如何告诉线程哪个面板是它自己的面板?

So how can I tell a thread which Panel is its own Panel?

推荐答案

创建线程类时,添加一个变量来存储面板ID:

When you create a thread class, add a variable to store panel id:

type
TMyThread = class(TThread)
public
  PanelId: integer;
  constructor Create(APanelId: integer);
end;

constructor TMyThread.Create(APanelId: integer);
begin
  inherited Create({CreateSuspended=}true);
  PanelId := APanelId;
  Suspended := false;
end;

为每个线程创建一个面板并将其Tag值设置为此ID:

For every thread create a panel and set it's Tag value to this Id:

for i := 1 to MaxThreads do begin
  threads[i] := TMyThread.Create(i);
  panels[i] := TPanel.Create(Self);
  panels[i].Tag := i;
end;

当线程需要在面板上更新数据时,它应该向主表单发送一条特殊定义的消息:

When your thread needs to update data on panel, it should send a specially defined message to the main form:

const
  WM_CONNECTED = WM_USER + 1;
  WM_DISCONNECTED = WM_USER + 2;

在此消息的wParam中,您传递PanelId:

In wParam of this message you pass PanelId:

procedure TMyThread.Connected;
begin
  PostMessage(MainForm.Handle, WM_CONNECTED, PanelId, 0);
end;

在MainForm中,您会收到以下消息,找到面板并进行更新:

In MainForm you catch this message, find the panel and update it:

TMainForm = class(TForm)
  {....}
protected
  procedure WmConnected(var msg: TMessage); message WM_CONNECTED;
end;

{...}

procedure TMainForm.WmConnected(var msg: TMessage);
begin
  panels[msg.wParam].Color := clGreen;
end;

与WmDisconnected相同.

Same with WmDisconnected.

这里重要的是,您不能也不应该尝试从主线程以外的线程更新可视组件.如果需要更新用户控件,则应将消息发布到主表单并创建处理程序过程,如本示例中所示.然后,将从主线程自动调用这些处理程序过程.

The important thing here is that you CANNOT and NEVER should try to update visual components from threads other than the main thread. If you need to update user controls, you should post messages to the main form and create handler procedures, like in this example. These handler procedures will then be automatically called from the main thread.

这篇关于为每个线程分配一个面板-Delphi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆