正在编写一个检测USB插入的程序,并将插入的驱动器保存到StringList。 现在我想为StringList的每个内容创建一个NewTask或Background Worker,立即启动它们并等到所有任务完成后使用OmniThread库。
这是我的代码段
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes,
Winapi.ShellApi, OtlCommon,
OtlCollections,
OtlParallel, Vcl.Dialogs;
procedure TUSB.WMDeviceChange(var Msg: TMessage);
var
lpdbhHeader: PDevBroadcastHeader;
ResStringList, TempSenderList: TStringList;
i: Integer;
begin
lpdbhHeader := PDevBroadcastHeader(Msg.LParam);
ResStringList := TStringList.Create;
TempSenderList := TStringList.Create;
ResStringList.Clear;
TempSenderList.Clear;
try
case Msg.WParam of
DBT_DEVICEARRIVAL:
begin
if (lpdbhHeader^.dbch_devicetype = DBT_DEVTYP_VOLUME) then
begin
Sleep(2000);
// Procedure to get connected USB Devices and save to a StringList
(GetDrive(PDevBroadcastVolume(Msg.LParam), ResStringList));
for i := 0 to ResStringList.Count - 1 do
begin
{ How do I create a NewTask or
Background Worker for each content in ResStringList
to execute WalkDirectory and Parallel.ForEach(0, TempSenderList.Count - 1)
in the NewTask? }
// Procedure to Recurse content of the USB Drive and Save to TempSenderList
WalkDirectory(ExcludeTrailingPathDelimiter(ResStringList.Strings
[i]), TempSenderList);
Parallel.ForEach(0, TempSenderList.Count - 1).Execute(
procedure(const value: Integer)
begin
// DoSomeThing(TempSenderList[value]);
end);
ShowMessage(TempSenderList.Text);
end;
end;
end;
DBT_DEVICEREMOVECOMPLETE:
begin
if (lpdbhHeader^.dbch_devicetype = DBT_DEVTYP_VOLUME) then
begin
// ShowMessage('Removed');
end;
end;
end;
finally
ResStringList.Free;
TempSenderList.Free;
end;
end;
使用Delphi XE7和OmniThread Library v3.04。