Creating NewTask in a For Loop using Omnithread Library

218 Views Asked by At

am writing a program that detects USB Insertion and saves the Inserted Drive(s) to a StringList. Now I want to create a NewTask or Background Worker for each Content of the StringList, start them immediately and wait till all task finishes using OmniThread Library.

Here is my Code Snippet

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;

Using Delphi XE7 and OmniThread Library v3.04.

0

There are 0 best solutions below