0

我正在用C#编写一个库,允许我将 HTML 转换为 PDF。显然,这个想法是它是跨平台的,也是我使用单声道的原因。为此,我必须使用System.Drawing.Text.PrivateFontCollection类加载卖方字体。

当应用程序完成执行所有代码时,应用程序意外退出。经过多次测试,我意识到问题在于何时调用Dispose 方法System.Drawing.Text.PrivateFontCollection或何时调用Dispose()of System.Drawing.FontFamily

这个问题在Windows中(我有 Windows 7 32 位),在linux 中我没有问题

这是测试代码

using System;
using System.Drawing.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing;

namespace FORM
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            PrivateFontCollection pf = new PrivateFontCollection ();
            IntPtr fontBuffer = IntPtr.Zero;
            pf.AddFontFile ("C:\\Users\\James\\Downloads\\open sans\\open-sans.regular.ttf");

            Font f = new Font (pf.Families[0],12,FontStyle.Regular);

            try {
                pf.Dispose ();
            }
            catch{
            }
            pf = null;
            Console.WriteLine ("Hello World!");
            Console.ReadLine ();

            //pf.Dispose ();
        }
    }
}
4

1 回答 1

0

总是打电话Dispose吗?

Dispose使用非托管资源时需要始终调用。

另一种调用 Dispose 的方法是使用using关键字...

示例(在运行此之前,请在您的电脑上重新启动以确保所有资源已被释放):

using System;
using System.Drawing.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing;

namespace FORM
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            using (PrivateFontCollection pf = new PrivateFontCollection())
            {
                IntPtr fontBuffer = IntPtr.Zero;
                pf.AddFontFile("C:\\Windows\\Fonts\\times.ttf");

                Font f = new Font(pf.Families[0], 12, FontStyle.Regular);
            }

            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }
    }
}
于 2014-03-21T14:09:32.507 回答