作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当用户单击“取消”按钮或关闭/销毁表单时,我需要以最快的方式退出TParallel.For
循环。我已经尝试了TParallel.TLoopState.Stop
和TParallel.TLoopState.Break
:
var
BreakCondition: Boolean;
procedure TForm2.DoStartLoop;
begin
BreakCondition := False;
System.Threading.TParallel.For(1, 50,
procedure(idx: Integer; LS: TParallel.TLoopState)
begin
if BreakCondition then
begin
//LS.&BREAK;
LS.STOP;
//EXIT;
end
else
DoProcessValue(idx);
end);
end;
TParallel.TLoopState.Stop
和
TParallel.TLoopState.Break
文档仅说明了以下内容:
Embarcadero Technologies does not currently have any additional information.
最佳答案
From the TParallel.For
documentation:
If control of the iteration itself is needed from the iterator event, the iterator event handler should be one using the
TParallel.TLoopState
parameter. When present, the event handler will be given an instance ofTParallel.TLoopState
from which state information fromFaulted
,Stopped
, orShouldExit
can be monitored, or the iteration loop itself can be controlled with theBreak
orStop
methods.
TIteratorStateEvent =
procedure (Sender: TObject; AIndex: Integer; const LoopState: TLoopState) of object;
class function &For(AStride, ALowInclusive, AHighInclusive: Integer;
const AIteratorEvent: TProc<Integer, TLoopState>; APool: TThreadPool): TLoopResult;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TLoopState = class
private [...]
public
procedure Break;
procedure Stop;
function ShouldExit: Boolean; <<-- this looks useful
property Faulted: Boolean read GetFaulted;
property Stopped: Boolean read GetStopped; <<-- or this
property LowestBreakIteration: Variant read GetLowestBreakIteration;
end;
procedure TForm1.btnParallelForClick(Sender: TObject);
var
Tot: Integer;
SW: TStopwatch;
begin
try
// counts the prime numbers below a given value
Tot :=0;
SW :=TStopWatch.Create;
SW.Start;
//Use a method that supports LoopState
TParallel.For(2,1,Max,procedure(I:Int64; State: TLoopState)
begin
//check loopstate every now and again.
if State.ShouldExit then exit;
if IsPrime(I) then TInterlocked.Increment(Tot);
end);
SW.Stop;
Memo1.Lines.Add(Format('Parallel For loop. Time (in milliseconds): %d - Primes found: %d', [SW.ElapsedMilliseconds,Tot]));
except on E:EAggregateException do
ShowMessage(E.ToString);
end;
end;
关于multithreading - 退出Parallel.For循环的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43790289/
我是一名优秀的程序员,十分优秀!