易截截图软件、单文件、免安装、纯绿色、仅160KB

Delphi多线程学习(10):Label(VCL)同步的问题

上文中,多线程同步主窗体的Label的Caption属性值,发现一个问题:使用Synchronize用于同步的时候,主窗体好像死掉一样;而直接用子程序为Label的引用赋值,则有时会出现“Canvas  does not allow drawing”错误。书上说VCL同步一定要用Synchronize,而不能直接访问。
    测试:
{主窗体}
unit Unit2;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm2 = class(TForm)
Label1: TLabel;
Button1: TButton;
Label2: TLabel;
Label3: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form2: TForm2;

implementation

uses TestThread;

{$R *.dfm}

procedure TForm2.Button1Click(Sender: TObject);
begin
TTestThread.Create(Label1);
//TTestThread.Create(Label2);
//TTestThread.Create(Label3);
end;

end.{多线程类}
unit TestThread;

interface

uses
Classes,StdCtrls;

type
TTestThread = class(TThread)
private
{ Private declarations }
FLabel:TLabel;
Fstr:string;
procedure UpdateLabel;
protected
procedure Execute; override;
public
constructor Create(Lab:TLabel);
end;

implementation

uses Unit2,SysUtils,windows;

{ TTestThread }

constructor TTestThread.Create(Lab: TLabel);
begin
FLabel:=Lab;
Inherited Create(False);
FreeOnTerminate:=True;
end;

procedure TTestThread.Execute;
var
i:Integer;
begin
{ Place thread code here }
for i := 0 to 20000 do
begin
if Not Terminated then
begin
Fstr:=Format('线程ID:%d,第%d个循环',[GetCurrentThreadID,i]);
//UpdateLabel;
Synchronize(UpdateLabel);
end;
end;

end;

procedure TTestThread.UpdateLabel;
begin
FLabel.Caption:=Fstr;
end;

end.
经过测试,只创建一个线程,用Synchronize同步主窗体的一个Label,那么程序无问题,可以见到同步的过程。当�


相关文档:

Delphi调试DLL 不能调试 不能进入调试 注意!!!

如何调试DLL,在这里就不再赘述了,但是,今天就碰到了一个特别奇怪的问题,参数设置正确,就是不能调试?? 通过上网查资料,发现了问题,注意:
  1, 将Project主菜单的Project Options对话框的Compiler页面Debugging选项中的 Debug informaton、Local symbols、Assertions复选框选中
  2,将Tools主菜单的D ......

Delphi 资源文件使用


Delphi使用资源文件全攻略
   在通常情况下使用delphi设计程序,都是将字符串、图像等资源直接使用delphi提供的vcl控件加到*.dfm中,这样做会合修改这些资源时带来不便,如果资源被多次引用,这些资源在程序启动时都被加载到内存中,非常耗费系统资源。因此,这就需要一种新的引用资源的文件:资源文件。资源 ......

Delphi多线程学习(2):Delphi中的多线程类TThread。

2010-02-22 17:08:46
Delphi把多线程相关的API封装在TThread这个类中,可以方便实现多线程运用。首先看下TThread的声明:
TThread = class

private
FHandle: THandle;
FThreadID: THandle;
FCreateSuspended: Boolean;
FTerminated: Boolean;
FSuspended: Boolean;
FFreeOnTerminate: ......

Delphi多线程学习(6):信号量Semaphore

信号量是建立在互斥量的基础之上,同时加入重要特性:提供了资源计数功能,因此预定义数量的线程同时可以进入同步的代码块中。
      信号量是维护0到指定最大值之间的计数器的同步对象,当线程完成一次信号量的等待时,计数器自减1,当线程释放信号量对象时,计数器自增1。
    ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号