Avatar of Dein
Dein

asked on 

Object is currently in use elswhere exception when doing Graphics.DrawString()

I have a project in which I draw maps by using GDI+.
The maps are drawn in a webservice and are therefore drawn in multiple threads.
Sometimes when executing a certain statement in my code (Graphics.DrawString()) i get an 'Object is currently in use' exception.
In each thread (request to the webservice) a new Graphics object is created by Graphics.FromImage() and a lot of lines and polygons are drawn on this graphics without any problems or exceptions.
On the map I also need to draw som text (roadnames) which should follow the road lines. To do that I draw each character one at a time rotated, so the name follows the line. It is in that part of code the exception occurs.

A simplifyed version of the code can be seen below. The code is executed one time pr. character to draw.

Can anyone tell me what is wrong with this code or how I can avoid exceptions from g.DrawString()?

The code works fine when not running multithreaded.
// GraphicState is saved (this is the graphic that all the roads are drawn at)
System.Drawing.Drawing2D.GraphicsState state = g.Save();
 
// Graphic tranformed and rotated
g.TranslateTransform(point.X, point.Y); // Point of character to draw
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.RotateTransform(angle); // Angle by which to draw
 
// And here the character is drawn and this is the statement throwing exceptions once in a while when other threads are also drawing 
g.DrawString(character.ToString(), font, textBrush, drawP);
 
// GraphicState restore
g.Restore(state);

Open in new window

.NET Programming

Avatar of undefined
Last Comment
Dein

8/22/2022 - Mon