[DUG] Best way to make this thread safe
Matt Comb
matt at ferndigital.com
Thu May 17 09:48:59 NZST 2007
Because you are utilizing a control on your main form (i.e. your main
thread), you must call synchronize in order to force your main thread to
stop what its doing and run your log call. This will insure that the UI is
not using that control when you decide to play around with it.
Excuse Pigeon code...
e.g.
TSomeThread = class(TThread)
FErrorText: string;
Property ErrorText: string read FErrorText write FErrorText; Procedure
InternalLogStuff Procedure LogStuff(LogMessage)'
And then in code you would do the following
Blah blah
Procedure LogStuff(LogMessage: string);
Begin
ErrorText := LogMessage;
Synchronize(InternalLogStuff);
End;
Procedure InternalLogStuff;
Begin
Do Whatever you have to do to log it.
End;
Regards,
Matt.
-----Original Message-----
From: delphi-bounces at delphi.org.nz [mailto:delphi-bounces at delphi.org.nz] On
Behalf Of Nick
Sent: Thursday, 17 May 2007 9:08 a.m.
To: NZ Borland Developers Group - Delphi List
Subject: [DUG] Best way to make this thread safe
I got a function here I use for logging to a richedit on my main form
(this is just in functions unit)
Procedure WriteLog(sString : string; opt : LogOption);
Begin
With frmMain.reLog do
begin
If lines.Count > 200 then lines.Delete(0);
lines.add(sString);
SelStart := length(text) - (length(sString)+2);
SelLength := length(sString);
Case LogOption(opt) of
loStart : begin SelAttributes.Style := [fsbold];
SelAttributes.Color := clBlue; end;
loNormal : begin SelAttributes.Style := [];
SelAttributes.Color := clBlack; end;
loError : begin SelAttributes.Style := [fsbold];
SelAttributes.Color := clRed; end;
loFinished: begin SelAttributes.Style := [fsbold];
SelAttributes.Color := clBlue; lines.add(''); end;
End;
SelStart := Length(Text);
Perform(EM_SCROLLCARET, 0, 0);
end;
End;
Now I want to use that function in my threads to log things. However if
I call it just like this
WriteLog('Failed to connect! DB Error', loError);
I could run into access violations
But not quite sure the best way to do this to make it thread safe and
use as little extra code as possible..
Should I create my own function like this
WriteLogThread('Failed to connect! DB Error', loError);
in my TThread
and then in that procedure just do
criticalsection start
WriteLog(message, st); //this calls the function in my general
functions unit
criticalsection end
or could I just use critical sections in my functions unit around the
procedure.
I hope that makes sense =)
Thanks guys.
_______________________________________________
NZ Borland Developers Group - Delphi mailing list
Post: delphi at delphi.org.nz
Admin: http://delphi.org.nz/mailman/listinfo/delphi
Unsubscribe: send an email to delphi-request at delphi.org.nz with Subject:
unsubscribe
More information about the Delphi
mailing list