parallel.foreach를 중단 하시겠습니까?
어떻게 밖으로 휴식 할 parallel.for 루프?
다음과 같은 매우 복잡한 진술이 있습니다.
Parallel.ForEach<ColorIndexHolder>(ColorIndex.AsEnumerable(),
new Action<ColorIndexHolder>((ColorIndexHolder Element) =>
{
if (Element.StartIndex <= I && Element.StartIndex + Element.Length >= I)
{
Found = true;
break;
}
}));
병렬 클래스를 사용하면이 프로세스를 훨씬 최적화 할 수 있습니다. 하나; 병렬 루프를 끊는 방법을 알 수 없습니까? break;
문은 다음과 같은 구문 오류가 발생합니다 :
중단하거나 계속할 엔 클로징 루프 없음
ParallelLoopState.Break
방법을 사용하십시오 :
Parallel.ForEach(list,
(i, state) =>
{
state.Break();
});
또는 귀하의 경우 :
Parallel.ForEach<ColorIndexHolder>(ColorIndex.AsEnumerable(),
new Action<ColorIndexHolder, ParallelLoopState>((ColorIndexHolder Element, ParallelLoopState state) =>
{
if (Element.StartIndex <= I && Element.StartIndex + Element.Length >= I)
{
Found = true;
state.Break();
}
}));
당신의 과부하 사용하여 호출하여이 작업을 수행 Parallel.For
하거나 Parallel.ForEach
루프 상태에 전달하는 다음 호출 ParallelLoopState.Break
또는 ParallelLoopState.Stop
. 가장 큰 차이점은 사물이 얼마나 빨리 깨지는 지에 있습니다 Break()
. 루프는 현재보다 더 이른 "인덱스"를 가진 모든 항목을 처리합니다. 를 사용하면 Stop()
가능한 한 빨리 종료됩니다.
자세한 내용은 방법 : Parallel.For 루프에서 중지 또는 중단을 참조하십시오 .
당신이 사용해야 Any
하는 것은 foreach 루프가 아니라입니다 :
bool Found = ColorIndex.AsEnumerable().AsParallel()
.Any(Element => Element.StartIndex <= I
&& Element.StartIndex + Element.Length >= I);
Any
결과가 사실이어야한다는 사실을 알게되는 즉시 멈출 수있을만큼 똑똑합니다.
LoopState는 확실히 훌륭한 대답입니다. 이전 답변에는 다른 내용이 너무 많아서 답을 찾기가 어려웠으므로 여기에 간단한 경우가 있습니다.
using System.Threading.Tasks;
Parallel.ForEach(SomeTable.Rows(), (row, loopState) =>
{
if (row.Value == testValue)
{
loopState.Stop(); // Stop the ForEach!
}
// else do some other stuff here.
});
loopState
제공 할 수 있는 것을 사용하십시오 .
Parallel.ForEach<ColorIndexHolder>(ColorIndex.AsEnumerable(),
new Action<ColorIndexHolder>((Element, loopState) => {
if (Element.StartIndex <= I && Element.StartIndex + Element.Length >= I) {
loopState.Stop();
}
}));
참고 URL : https://stackoverflow.com/questions/12571048/break-parallel-foreach
'programing tip' 카테고리의 다른 글
Java의 모듈러스가 음수로 작동하도록하는 가장 좋은 방법은 무엇입니까? (0) | 2020.08.28 |
---|---|
bash 쉘 스크립트에 파일을 포함하는 방법 (0) | 2020.08.28 |
클릭 된 항목과 RecyclerView에서 해당 위치 가져 오기 (0) | 2020.08.28 |
PreparedStatement를 여러 번 재사용 (0) | 2020.08.27 |
슈퍼 클래스 생성자를 언제 명시 적으로 호출해야합니까? (0) | 2020.08.27 |