Hi,
I'm getting "object is currently in use elsewhere" when I use
System.Drawing.Graphics.MesureString.
This is what I do:
My controls use a utility class the helps it to mesure strings.
To get the best performance for the utility class, its members, as well as
the System.Drawing.Graphics object, are static:
internal sealed class Utils
{
static System.Drawing.Bitmap oBmp;
static System.Drawing.Graphics oGrf;
.....
.....
}
The members are initialized in the static constructor:
static Utils()
{
oBmp = new System.Drawing.Bitmap(100, 150); //dummy numbers
oGrf = new System.Drawing.Graphics.FromImage(oBmp);
oGrf.PageUnit = System.Drawing.GraphicsUnit.Pixel;
.....
.....
}
In that way there is only one object for the controls.
Every control calls this method one time when the control is loading:
public static float CalcStringLength(string InText)
{
System.Drawing.SizeF oSizeF = oGrf.MesuereString(InText, oFontInfo);
return oSizeF.Width;
}
The problem is that when 10 users try to activate 10 controls that call to
CalcStringLength I get this error:
"the object is currently in use elsewhere"
I know this object is meant to be disposed but because it is static I have
no idea when to dispose it...
This didn't help either:
public static float CalcStringLength(string InText)
{
try
{
System.Drawing.SizeF oSizeF = oGrf.MesuereString(InText, oFontInfo);
return oSizeF.Width;
}
catch
{
// restart the graphic object
oGrf.Dispose;
oGrf = System.Drawing.Graphics.FromImage(oBmp);
return CalcStringLength(InText);
}
}
Is there any way that I can work with the graphic object as static object
without getting this error?
Thanks in advance,
Hadar.