好的,情况如下:我的主/UI 线程(称为 Thread1)用于从物理文档扫描仪获取一批图像。获取批次后,将启动一个单独的“背景”线程(称为 Thread2)以处理和保存该批次中的图像。
Thread2(“后台”线程)正在使用一个Parallel.For
循环,与正常循环相比,该循环将图像处理/保存时间减少了 70% For
。但是,它似乎也使我的所有处理器都达到极限,因此 Thread1 在Parallel.For
循环完成之前无法开始获取更多图像。
有没有办法“限制”一个Parallel.For
循环,使其不会最大化我的处理器?或者设置处理优先级?我试过设置Thread2.Priority = ThreadPriority.Lowest
,但这似乎不会影响循环。还是我误解了Parallel.For
循环的工作原理?它是否以某种方式阻塞了 Thread1?
下面是我如何从 Thread1 中的方法调用 Thread2。
public void SaveWithSettings(bool save) // method in Thread1
{
....
Thread thr = new Thread(ThreadWork); // creating new thread (Thread 2)
thr.Priority = ThreadPriority.Lowest; // does nothing?
thr.Start(new SaveContainer(sc)); // pass a copy as paramater
// misc stuff to make scanning possible again
numBgw++;
twain.RemoveAllImages(); // clear images
imagelist.Clear(); // clear imagelist images
.... // etc. this all appears to process fine while Thread2 is processing
}
这是我的ThreadWork
方法:
private void ThreadWork(object data) // executing in Thread2
{
SaveContainer sc = data as SaveContainer; // holds images
bool[] blankIndex = new bool[sc.imagelist.Count]; // to use in Parallel.For loop
for (int i = 0; i < sc.imagelist.Count; i++)
blankIndex[i] = false; // set default value to false (not blank)
Parallel.For(0, sc.imagelist.Count, i => // loop to mark blank images
{
bool x = false; // local vars make loop more efficient
x = sc.IsBlankImage((short)i); // check if image at index i is blank
blankIndex[i] = x; // set if image is blank
}
.... // other image processing steps
}