【问题标题】:Why application crash when i use PrivateFontCollection.Dispose() in mono3.2.3 c#?为什么当我在 mono3.2.3 c# 中使用 PrivateFontCollection.Dispose() 时应用程序崩溃?
【发布时间】:2014-04-28 22:18:08
【问题描述】:

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

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

这个问题在 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 ();
        }
    }
}

【问题讨论】:

    标签: c# fonts mono system.drawing privatefontcollection


    【解决方案1】:

    总是打电话给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();
            }
        }
    }
    

    【讨论】:

    • PrivateFontCollection 和 FontFamily 是 IDisposable,这意味着虽然没有显式调用该方法,但当应用程序关闭时会调用 Dispose 方法。对我来说,这是一个单声道错误,但想知道在纠正时是否有人知道任何解决方案
    • 你说得对...Dispose方法是自动调用的,但是.net框架不保证什么时候会调用它...而且还有您的问题...您很可能正在尝试访问尚未释放的资源(即 Dispose 尚未运行)
    • 不,不是我的问题。考虑不调用 Dispose 方法的代码,无论如何应用程序都会失败。问题在于单声道而不是.net,并且仅在 Windows 中,而不是在 Linux 中
    • 在你的电脑上用单声道运行代码,应用程序崩溃,不管你是否调用 dispose 方法
    • 嗯,我真的没有一台带单声道的 PC 来试试这个......不过,我上面发布的代码是在 .net framework 4.0 上测试的,它没有产生任何异常......也许其他人可以帮助您...无论如何,您应该始终在使用非托管资源(无论是使用 mono 还是 .net)后立即调用 dispose...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    相关资源
    最近更新 更多