使用DrawString()时出现GDI+异常

3

我正在尝试使用条形码字体创建条形码图像时遇到错误。这在生产环境中发生,但在开发环境中没有出现此问题。

创建条形码的方法是:

/// <summary>
/// Create a barcode image by writing out a string using a barcode font and save it
/// </summary>
/// <param name="barcodeText">The text string of the barcode</param>
/// <param name="saveLocation">Where to save the file to</param>
/// <param name="font">The barcode font</param>
/// <param name="imageFormat">The image format</param>
private void CreateBarcodeImage(string barcodeText, string saveLocation, System.Drawing.Font font, ImageFormat imageFormat)
{
    // Draw the barcode image
    using (Bitmap bmp = new Bitmap(500, 75))
    {
    try
    {
        using (Graphics g = Graphics.FromImage(bmp))
        {
        g.Clear(_backgroundColour);
        g.DrawString(barcodeText, font, _foregroundBrush, 10, 0);
        bmp.Save(saveLocation, imageFormat);
        g.Dispose();
        }
    }
    catch (Exception ex)
    {
        Log.ErrorException("Exception in LabelPrinter.CreateBarcodeImage()", ex);
        throw;
    }
    }
}

这段代码正在循环调用,因为需要多个条形码。在开发环境中它可以正常工作,但在实际环境中(在Win XP Pro上使用.net 3.5 SP1在winforms应用程序中),创建了两个条形码并在第三次时引发了异常。

引发的异常和堆栈跟踪如下:

An unhandled exception has occurred Attempted to read or write protected memory. This is often an indication that other memory is corrupt. 
at System.Drawing.SafeNativeMethods.Gdip.GdipMeasureString(HandleRef graphics, String textString, Int32 length, HandleRef font, GPRECTF& layoutRect, HandleRef stringFormat, GPRECTF& boundingBox, Int32& codepointsFitted, Int32& linesFilled) 
at System.Drawing.Graphics.MeasureString(String text, Font font, SizeF layoutArea, StringFormat stringFormat) 
at System.Drawing.Graphics.MeasureString(String text, Font font) 
at Srcl.WasteTrak.Gui.Documents.LabelPrinter.CreateBarcodeImage(String barcodeText, String saveLocation, Font font, ImageFormat imageFormat) 
in c:\scc\SRCL\SRCL.WasteTrak\SRCL.WasteTrak.Gui\Documents\LabelPrinter.cs:line 60 

我找不出是什么原因导致了这个问题,但从谷歌搜索来看似乎是调用非托管代码引起的,但我还没有找到解决方案。

有人能帮忙吗?


你尝试过使用不同的字体来看看是否有所不同吗?顺便说一下,你在 Graphics 对象上调用了两次 .Dispose()。 - Dan Byström
是的,我尝试过使用不同的字体(当前的是条形码字体),并且我使用了另一个(普通的)嵌入式字体,还引用了系统字体,但结果仍然相同。 已经删除了g.Dispose(),但结果仍然相同。 - Ciaran O'Neill
应用程序是通过ClickOnce部署的 - 我想知道这是否是问题的一部分。 - Ciaran O'Neill
那么你的意思是即使使用不同的字体,问题仍然存在?嗯,你确定在绘制时字体没有被释放吗?_foregroundBrush也是一样。 - Dan Byström
1
这个问题是在多台电脑上出现的还是只有一台?(生产环境)而且这个问题在多个开发者电脑上工作了吗,还是只有一个?你最终解决了这个问题吗? - Steffen Winkler
1个回答

0

你能试着移除下面这行代码吗?

g.Dispose();

使用using语句将自动释放它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接