多线程中动态创建TRICHEDIT的释放问题!!!!!急急,请大侠指点!!(50分)

  • 主题发起人 主题发起人 zqy29
  • 开始时间 开始时间
Z

zqy29

Unregistered / Unconfirmed
GUEST, unregistred user!
我的程序是用多线程做的,当起一个线程时,我就创建一个TabSheet,并在此TabSheet上创建一个TRichEdit,当线程创建多个时,TRichEdit也就创建多个了,当线程释放时,TRichEdit也随之释放,这个在创建线程比较慢时就不会出什么问题,但如果线程创建太快的话,释放TRichEdit和TabSheet时就会报错,好像说是找不到对象,这是为何?????请各们高手指点!!

constructor TMyServerThread.Create(CreateSuspended: Boolean;
ASocket: TServerClientWinSocket;
Thread_Id : integer;
pMainRedt:TRichEdit);
//pNewRichEdit,
begin
inherited Create(CreateSuspended, ASocket);
NewMsgRichEdit := Frm_Main.GetNewMsgRichEdit;
//pNewRichEdit;
end;

destructor TMyServerThread.destroy;
begin
if Self.NewMsgRichEdit <> nil then
Synchronize(InternalFree);
gThreadHandle[ThreadId_Number] := nil;
inherited;
end;

function TFrm_Main.GetNewMsgRichEdit():TRichEdit;
var
ltbs: TTabSheet;
lredt : TRichEdit;
begin
ltbs:= TTabSheet.Create(Self.PageControl1);
ltbs.Caption:= 'Thread';
lredt:= TRichEdit.Create(ltbs);
lredt.Parent:= ltbs;
ltbs.PageControl:= Self.PageControl1;
lredt.Align:= alClient;
lredt.ScrollBars := ssBoth;
Result:= lredt;
end;

procedure TMyServerThread.InternalFree;
begin

FMainRedt.SelStart := Length(FMainRedt.Lines.Text) + 1;
FMainRedt.SelLength := 0;
FMainRedt.SelAttributes.Color := clBlue;
FMainRedt.Lines.Add(#10 + '>>>>>>>>>>>>>>>>>>>Thread begin
<<<<<<<<<<<<<<<<<<<<');
FMainRedt.SelAttributes.Color := clNone;
FMainRedt.Lines.Add(Self.NewMsgRichEdit.Lines.Text);
FMainRedt.SelStart := Length(FMainRedt.Lines.Text) + 1;
FMainRedt.SelLength := 0;
FMainRedt.SelAttributes.Color := clBlue;
FMainRedt.Lines.Add('>>>>>>>>>>>>>>>>>>>>Thread End<<<<<<<<<<<<<<<<<<<<<' + #10);
FMainRedt.SelAttributes.Color := clNone;
Self.NewMsgRichEdit.Lines.Clear;
Self.NewMsgRichEdit.Parent.Free;
end;

procedure TMyServerThread.AddLogToREdt(log: String;
logcolor : TColor=clNone);
begin
Self.MyMsg := ' ' + log;
Self.MyColor := logColor;
// Frm_Main.PageControl1.ActivePageIndex := 0;
Synchronize(Self.addMsg);
end;

procedure TMyServerThread.addMsg;
begin
Self.MyMsg := FormatDateTime('yyyy-mm-dd hh:nn:ss', Now()) + Self.MyMsg;
if Self.MyColor = clNone then
begin
if Self.NewMsgRichEdit <> Nil then
Self.NewMsgRichEdit.Lines.Add(Self.MyMsg);
end
else
begin
if Self.NewMsgRichEdit <> Nil then
begin
Self.NewMsgRichEdit.SelStart := Length(Self.NewMsgRichEdit.Lines.Text) + 1;
Self.NewMsgRichEdit.SelLength := 0;
Self.NewMsgRichEdit.SelAttributes.Color := MyColor;
Self.NewMsgRichEdit.Lines.Add(Self.MyMsg);
end;
end;
end;

提示错误信息“Failed to set object at index 2” 或“System Error Code.5 拒绝访问”
 
你这样是滥用线程,VCL不是线程安全的,所以所有关于VCL界面的操作最后全部放在主线程中处理,子线程一般用来处理需要长时间耗时的运算或IO操作工作,完成的时候再通过发送消息等方式通知主线程刷新界面反馈给用户
 
接受答案了.
 

Similar threads

后退
顶部