からコードを使用すると、バックグラウンドで長時間の操作を実行したいので、ここに行くための方法ではありませんです。バッチファイルを実行すると、バッチファイルに時間がかかる場合、現在の方法でバッチファイルを実行するとユーザーがブロックされます。
より良いアプローチ:明示的なスレッドを使用する。 TThreadの子孫として独自のスレッドクラスを作成します。クラスの各インスタンスには、連続して実行されるように注意を払う特定のファイル名が与えられます。
unit BatchExecutionThread;
interface
uses Classes;
type
TBatchExecutionThread = class (TThread)
private
pBatchFileToExecute: string;
public
constructor Create(ABatchFileToExecute: string);
procedure Execute; override;
end;
implementation
uses SysUtils, Windows;
constructor TBatchExecutionThread.Create(ABatchFileToExecute: string);
begin
inherited Create;
pBatchFileToExecute := ABatchFileToExecute;
end;
procedure TBatchExecutionThread.Execute;
begin
{ While no stop requested }
while(not Terminated) do
begin
try
{ Execute Batch file if it exists }
if FileExists(pBatchFileToExecute) then
begin
ExeAndWait(pBatchFileToExecute, SW_SHOWNORMAL);
end;
except
{ Ignore exception }
end;
{ Wait a second }
Sleep(1000);
end;
end;
end.
次に、アプリケーションから、実行するファイルごとにこのスレッドクラスのさまざまなインスタンスをたくさん作成することができます。
は、たとえば次のように:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, BatchExecutionThread, System.Generics.Collections;
type
TForm1 = class(TForm)
ButtonStart: TButton;
ButtonStop: TButton;
procedure ButtonStartClick(Sender: TObject);
procedure ButtonStopClick(Sender: TObject);
private
pThreads: TList<TBatchExecutionThread>;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.ButtonStartClick(Sender: TObject);
var
i: Integer;
FileName: string;
Thread: TBatchExecutionThread;
begin
if(pThreads = nil) then
begin
{ Create a list where we store the running threads }
pThreads := TList<TBatchExecutionThread>.Create;
{ Create 10 threads with the batch file names from 1 to 10 }
for i:= 1 to 10 do
begin
{ Build the filename }
FileName := ExtractFilePath(Application.ExeName) + 'test'+ i.ToString() +'.bat';
{ Create a thread for this file }
Thread := TBatchExecutionThread.Create(FileName);
Thread.FreeOnTerminate := true;
{ Add the thread to the list }
pThreads.Add(Thread);
{ Start the thread }
Thread.Start();
end;
end;
{ else Already started }
end;
procedure TForm1.ButtonStopClick(Sender: TObject);
var
Thread: TBatchExecutionThread;
begin
if(pThreads <> nil) then
begin
{ Tell all threads to stop }
for Thread in pThreads do
begin
Thread.Terminate;
end;
{ Delete list of threads }
FreeAndNil(pThreads);
end;
{ else not started yet }
end;
end.
すべてが並行して動作する必要があります。 – waza123
コードのイメージはここではまったく役に立ちません。コードのイメージが受け入れられない多くの理由のリストについては、[this Meta post](http://meta.stackoverflow.com/a/285557/62576)を参照してください。また、フォームイメージも役に立たない。 (単にTTimerのすべてのコンポーネントを整理する方法を見せていない限り)質問には何のメリットもありません。 –
あなたはどのような問題を解決しようとしていますか?これは解決策ではありません。 –