请帮助Parallel.ForEach不使用图形 [英] Please help Parallel.ForEach is not working with graphics
本文介绍了请帮助Parallel.ForEach不使用图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
System.Threading.Tasks.Parallel.ForEach(ktl,rc=>
{
++i;
g.DrawRectangle(pen, rc);
g.DrawString("KN" + i.ToString(), new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold),
new SolidBrush(Color.Blue), rc.X, rc.Y);
}
);
但是这个工作
but this works
foreach (Rectangle rc in ktl)
{
++i;
g.DrawRectangle(pen, rc);
g.DrawString("KN"+i.ToString(), new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold),
new SolidBrush(Color.Blue), rc.X, rc.Y);
}
推荐答案
在图形 [ ^ ] - 他们说的类:
此类型的任何公共静态成员都是线程安全的。不保证所有实例成员都是线程安全的。
旁注:实现IDisposable的类的任何对象都应该在使用后进行处理,这可以通过在使用块中使用来实现,这是最容易实现的。 。您应该使用Font和Solidbrush执行此操作。由于它始终是相同的Font和SolidBrush,因此无需在循环的每次迭代中分配新的。
At the bottom of the MSDN-page for the Graphics[^]-class they state:
"Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe."
Sidenote: Any object of a class that implements IDisposable should be disposed after use, which can be easiest achieved by using it within a using-block. You should do this with your Font and Solidbrush. As it's always the same Font and SolidBrush, there's no need to allocate a new one in each iteration of your loop anyway.
这篇关于请帮助Parallel.ForEach不使用图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文