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

Anish
  • 812
  • 3
  • 19
  • 41
  • Are you sure the problem is with the `Brush`, not `Graphics` itself? – Michael Liu Sep 02 '13 at 02:16
  • Yes, Came to know that, Brush's are not thread safe – Anish Sep 02 '13 at 02:18
  • @Anish No, the problem is in `Graphics`, you can't draw on a `Graphics` object while it's being used, as far as I know, we don't have any solution to draw on a `Graphics` object with **multi-threading**. Someone said that we don't need threading to **speed** up the drawing, we just need to organize **how** we update the drawing to improve the drawing performance. I'm not sure but I also hope we can draw with **multi-thread**. – King King Sep 02 '13 at 03:28
  • @King King: Please see the link http://stackoverflow.com/questions/1060280/invalidoperationexception-object-is-currently-in-use-elsewhere-red-cross (Answer by Nick Gotch), when i used lock as in the above code the problem gets fixed. I was able to fix the issue by Nick's solution.. Here i want a good approach for my above code – Anish Sep 02 '13 at 04:32
  • @King king: Also here i'm not trying to speed up any thing using multithread.. My application get the drawing data or instruction from 2 external different source which acts independly – Anish Sep 02 '13 at 04:34
  • @Anish that seems to talk about `static brush`, I've also tried creating a list of different `Brushes`, `Pens`, `Graphics` and used in different threads, I could run the code for a long time but finally at some point the exception was thrown. – King King Sep 02 '13 at 05:00

1 Answers1

1

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.

James Hurst
  • 147
  • 9