线程安全在delphi [英] Thread-safe in delphi

查看:117
本文介绍了线程安全在delphi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的问题是如何编写,我必须修改和更改一个线程中的一些可视化组件,并且您知道这是不安全的。一个完全线程安全的代码?有可能吗?如果可以,请给我一个简单的例子?



我的不是线程安全的代码:

  type 
tMyWorkerThread = class(TThread)
public
procedure Execute;覆盖
结束

var
Form1:TForm1;

执行

{$ R * .dfm}

程序tMyWorkerThread.Execute;
begin
//代码
//使用视觉组件
end;

procedure TForm1.Button1Click(Sender:TObject);
begin
TMyWorkerThread.Create(false);
结束

谢谢。

解决方案

我的问题解决了同步!

 键入
tMyWorkerThread = class(TThread)
public
procedure Execute;覆盖
结束

var
Form1:TForm1;

执行

{$ R * .dfm}

程序tMyWorkerThread.Execute;
begin

//需要很长时间的代码
同步(程序开始
//使用可视化组件
end
);

end;

procedure TForm1.Button1Click(Sender:TObject);
begin
TMyWorkerThread.Create(false);
结束

感谢大家帮助我。


I have to modify and change some visual components in a thread and as you know it's not safe to doing this.

My question is how to write a completely thread-safe code? It is possible? if it is then can you please give me a simple example?

my code that is not threadsafe:

type
  tMyWorkerThread = class(TThread)
      public
         procedure Execute; override;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure tMyWorkerThread.Execute;
begin
  //codes
  //working with visual components
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  TMyWorkerThread.Create(false);
end;

Thank you.

解决方案

My problem solved with Synchronize!

type
  tMyWorkerThread = class(TThread)
      public
         procedure Execute; override;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure tMyWorkerThread.Execute;
begin

  //codes that takes long time
  Synchronize(procedure begin
     //working with visual components
  end
  );

end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  TMyWorkerThread.Create(false);
end;

Thank you all for helping me.

这篇关于线程安全在delphi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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