多线程快速操作tmemo时,乱码

MMas 2009-12-04 05:35:18
unit Unit1;

interface

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

type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

type
MyThread = class(TThread)
Fstr : string;
FMemo : TMemo;
constructor create(memo : TMemo; str : string);
procedure Execute; override;
end;


var
Form1: TForm1;
flag : boolean;

implementation

{$R *.dfm}

constructor MyThread.create(memo : TMemo; str : string);
begin
inherited create(true);
FreeOnTerminate := true;
FStr := str;
FMemo := Memo;
//Resume;
end;

procedure MyThread.Execute;
begin
while flag do Fmemo.Lines.Add(FStr);
sleep(1);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
MyTh : MyThread;
begin
flag := true;
MyTh := MyThread.create(self.Memo1, 'aaaaaaaaaaaaa');
myth.Resume;
MyTh := MyThread.create(self.Memo1, 'bbbbbbbbbbbbb');
myth.Resume;
MyTh := MyThread.create(self.Memo1, 'ccccccccccccc');
myth.Resume;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
flag := false;
end;

end.


以上代码测试时,MEMO滚动条设为BOTH,运行中,用鼠标向上选择里面的内容,有时就会出现添加行乱了。

我需要在多线程中向MEMO添加或更改行,在我的程序里,我在主线程和其它创建的线程中都使用同一个TCRITICALSECTION或MUTEX,但是还是在MEMO操作时乱了,有什么办法解决啊?我使用的是D6
...全文
90 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wintergoes 2009-12-04
  • 打赏
  • 举报
回复
那你就用criticalSection呗
不要用mutex,那个是进程级的,速度比较慢
Criticalsection是线程级的
EnterCriticalSection在主线程中是无效的,自己看看吧
liuchyx2007 2009-12-04
  • 打赏
  • 举报
回复
关注,帮顶
haitao 2009-12-04
  • 打赏
  • 举报
回复
不同步就不能直接操作vcl,
可以改为:线程把数据/信息放在一个变量里,主form通过定时器事件去取变量,决定加什么内容到memo
MMas 2009-12-04
  • 打赏
  • 举报
回复
这个方法可以,但是要同步的方法没有参数,不方便,而且,我要写的那个程序,线程是用API函数CREATETHREAD产生的,想用CRITICALSECTION或者MUTEX进行互斥写MEMO的操作。
wintergoes 2009-12-04
  • 打赏
  • 举报
回复

在线程里加入函数
procedure AddLog;

实现
procedure MyThread.Addlog;
begin
Fmemo.Lines.Add(FStr);
sleep(1);
end;


execute函数修改如下:

procedure MyThread.Execute;
begin
while flag do Synchronize(AddLog);
sleep(1);
end;

5,388

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧