0

I have an application where the UI get drawn from multiple threads. Some times i get an exception like "Object already in use". After searching a while i found that the usage of System.Drawing.Brush is causing the pblm. So i used lock just before using Brush. My problem here is i'm using lots of brush to draw data on the screen. what's the best practice to implement instead of using multiple locks like below. (Note: The class which is having the below code is initialized only once)

Brush redBrush = Brushes.Red;
lock(redBrush) {
    grph.DrawString(screenText1, this.Font, redBrush, rectangle, textFormat);
}


Brush blackBrush = Brushes.Black;
lock(blackBrush ) {
    grph.DrawString(screenText2, this.Font, blackBrush, rectangle, textFormat);
}

Brush blueBrush = Brushes.Blue;
lock(blueBrush ) {
    grph.DrawString(screenText3, this.Font, blueBrush, rectangle, textFormat);
}

Any help will be appreciated greatly

Thanks

4

1 回答 1

1

像这样在绘图代码中应用锁是非常不可取的。所指示的是一个基本的编码错误,并且是低效的。

尝试为每个需要它的线程提供一个画笔的副本,并冻结它们并使它们成为只读的,因为您不需要(大概)在创建画笔后自行修改它们。

于 2017-06-23T19:01:17.497 回答