gpt4 book ai didi

multithreading - 如何在Delphi XE7中同步TParallell以记录数据

转载 作者:行者123 更新时间:2023-12-03 18:58:24 24 4
gpt4 key购买 nike

我需要记录一些数据,最好使用线程复制文件,
但使用下面的代码,却只会冻结我的应用。

如果我正确理解了整个XE7 Parallell库,应该将TThread.QueueTThread.Synchronize与主线程同步,但是在我的情况下,整个应用程序将冻结。

我究竟做错了什么?

procedure TCopyDeviceContent.StartCopy;
var
OK: boolean;
begin
OK := false;

// showmessage('fFiles.Count = '+inttostr(fFiles.Count));

if fFiles.Count = 0 then
begin
NotifyDone;
exit;
end;

TParallel.For(0, fFiles.Count-1,
procedure (Value: Integer)
begin
TThread.Queue(TThread.CurrentThread, //Here is where it freezes
procedure
begin
Log('Setting fCurrentFile to '+fFiles.Strings[value]);
end
);

sleep(1000);

fCurrentFile := fFiles.Strings[value];
Log('Triggering fOnBeforeProcess');
if assigned(fOnBeforeProcess) then fOnBeforeProcess(self);

Log('Does file exist?');
if FileExists(fFiles.Strings[value]) = true then
begin
Log('Yes!');
Log('Trying to copy file to Windows temp folder.');
try
TFile.Copy(fFiles.Strings[value], GetEnvironmentVariable('TEMP'));
finally
OK := true;
end;

if OK = true then
begin
Log('Success!');
OK := false;

Log('Does file exist in Windows temp folder?');
if FileExists(GetEnvironmentVariable('TEMP')+ExtractFileName(fFiles.Strings[value])) then
begin
Log('Yes');
Log('Trying to copy file from Windows temp folder to final destination: '+DestPath+DateToStr(Now)+'\'+ExtractFileName(fFiles.Strings[value]));
try
TFile.Move(GetEnvironmentVariable('TEMP')+ExtractFileName(fFiles.Strings[value]),
DestPath+DateToStr(Now)+'\'+ExtractFileName(fFiles.Strings[value]));
finally
fFilesOK.Add(fFiles.Strings[value]);
Log('Sucess!');
end;
end;
end
else
begin
fFilesFailed.Add(fFiles.Strings[value]);
Log('Failed copying to Windows temp folder!');
end;
end;
inc(fProgress);
NotifyProgress;
Log('File copy success. Moving on to next file if available...');
end
);

NotifyDone;

if fFilesFailed.Count > 0 then NotifyError;
end;

最佳答案

如果目标只是在不冻结UI线程的情况下复制文件,我将使用类似以下内容:

procedure TCopyDeviceContent.StartCopy;
var
aTask: ITask;
begin
aTask := TTask.Create (procedure ()
begin
// Copy files here
TThread.Synchronize(nil,procedure
begin
//Interact with UI
Form1.Memo1.Lines.Add(‘Begin Execution’);
end);
end);
aTask.Start;
end;

在任务过程中,只需像通常那样复制文件即可,我不确定使用多个线程进行复制是否会对您有所帮助。

如果需要与UI交互,则需要切换回UI线程,可以使用TThread.Synchronize。

关于multithreading - 如何在Delphi XE7中同步TParallell以记录数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28964668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com