我正在使用Delphi 2007和线程。创建事件和共享变量
我的问题(对不起,我会试着解释更好):
1)我创建了一个文件“utilities.pas”在那里我有我使用更多的功能。 2)我创建了一个新程序,在这个程序中我有一个线程 3)在线程的执行方法中,我在文件“utilities.pas”中调用一个函数。 这个函数使用聪明的组件(tclftp)连接到一个ftp。这些组件记录服务器在专用事件中的响应。我想要做的是将日志保存在一个字符串列表中,然后将该字符串列表发送回调用线程。
这是文件的一部分 “utilities.pas”:
// I created TEventHandlers because it's the only way to assign the event runtime
// without having a class
type
TEventHandlers = class
procedure clFtp1SendCommand(Sender: TObject; const AText: string);
end;
var EvHandler: TEventHandlers;
// this is the porcedure called from the thread. i want to send the stringlist
// back to it containing the ftp log
procedure Test(VAR slMain: tStringlist);
var cFTP: TclFtp;
begin
cFTP := TclFtp.Create(nil);
cFTP.Server := 'XXX';
cFTP.UserName := 'XXX';
cFTP.Password := 'XXX';
cFTP.OnSendCommand := EvHandler.clFtp1SendCommand;
// i connect to the ftp
cFTP.Open;
FreeAndNil(cFTP);
end;
procedure TEventHandlers.clFtp1SendCommand(Sender: TObject; const AText: string);
begin
// here the component (cftp) sends me back the answer from the server.
// i am logging it
// HERE IT'S THE PROBLEM:
// I can't reach slMain from here.....
slmain.add(Atext);
end;
这是调用线程:
procedure TCalcThread.Execute;
var slMain: tstringlist;
begin
inherited;
slmain := tstringlist.create(nil);
Test(slmain);
if slMain.count > 0 then
slMain.savetofile('c:\a.txt');
// i won't free the list box now, but in the thread terminated.
end;
这是主要的程序:
procedure TfMain.ThreadTerminated(Sender: TObject);
Var ExThread: TCalcThread;
begin
ExThread := (Sender as TCalcThread);
if ExThread.slMain.Count > 0 then
ExThread.slMain.SaveToFile('LOG\Errori.log');
freeandnil(slMain);
end;
请任何人都可以帮助我解决这个问题吗?我真的不知道该怎么做。 我希望现在更清楚。
p.s.感谢所有的答案..
错字:slMail应该是:slMain –
我认为你需要调用cFTP.Open后做slMain什么?如果是这样,你应该发表评论。否则,正如所写,slMain是无关紧要的。 –
程序“Test”是否在线程中运行?如果是这样,你应该说清楚。 –