Anish
Anish

Reputation: 912

Issue in using Brush from multiple threads

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

Upvotes: 0

Views: 630

Answers (1)

James Hurst
James Hurst

Reputation: 147

Applying locks within your drawing-code like that is highly inadvisable. What is indicates is a basic coding mistake, and is inefficient.

Try providing a copy of the brush to each thread that needs it, and freezing them and making them readonly since you do not (presumably) need to modify the brushes themselves once they are created.

Upvotes: 1

Related Questions