English 中文(简体)
C# - Design-related dispose question (take two)
原标题:

I asked a question earlier today, but I think I need to approach it in a different way (on top of that there was a "hang up" in regards to DataSet).

Here s a class that encapsulates the creation of a Font (in other words, it is reading data from an xml file and is creating a font, at runtime, based on what it reads from that file):

public class FontCreator
{
    private Font m_TheFont = null;

    public FontCreator( ... some parameters ... )
    {
        m_TheFont = GetTheFont();
    }

    public Font TheFont
    {
        return m_TheFont;
    }

    private Font GetTheFont()
    {
        // code, and more code, that eventually leads to:

        Font f = new Font(fntFamily, fntSize, fntStyle);
        return f;
    }
}

The consumer of the FontCreator class looks something like:

public class TheConsumer()
{
    private FontCreator m_FontCreator = null;

    public TheConsumer()
    {
        m_FontCreator = new m_FontCreator( ... some parameters ... );
        Initialize();
    }

    private void Initialize()
    {
        InitializeThis();
        InitializeThat();
    }

    private void InitializeThis()
    {
        .... some code ...
        SomeObject.ApplyFont(m_FontCreator.TheFont);
    }

    private void InitializeThat()
    {
        ... some code ...
        SomeObject.ApplyFont(m_FontCreator.TheFont);
    }
}

What code do you add, and where, to ensure that "TheFont" s Dispose method is explicitly called?

最佳回答

If you don t wish to maintain a reference to TheFont after it is initially used, then call it s Dispose method in your constructor, right after Initialize. If you wish to keep TheConsumer alive for a while and maintain a reference to TheFont, it gets more interesting. Two Options:

  1. You can have TheFont s dispose method called from the Destructor of the TheConsumer object. This is not the common practice and has problems. Mainly, this is not called until garbage collection happens. Better is:
  2. You can make the TheConsumer object itself implement IDisposable, and call TheFont.Dispose from TheConsumer.Dispose. Since TheConsumer implements IDisposable, the code that uses it should call its Dispose method.

Edit in response to harsh comment! Yes, I should have made clear to only use 1 in addition to 2, if at all. I know all developers everywhere are supposed to notice when IDisposable is implemented, but they often don t. If the referenced managed resource might really remain around a long time and cause problems if not properly disposed, I sometimes have a safety Dispose() method call in the destructor of the object holding the reference. Is that so wrong? :)

问题回答
public TheConsumer()
{
    using (m_FontCreator = new m_FontCreator( ... some parameters ... ))
    {
        Initialize();
    }
}

I am confused, if you want to quickly use the font creater object then implement IDisposable on the FontCreater and use

using(m_FontCreator = new FontCreater(....))
{
   InitializeThis();
   InitializeThat();
}

If you need to keep the instance of the FontCreater through the lifetime of TheConsumer, then implement IDisposable on both FontCreater and TheConsumer classes.

public class TheConsumer : IDisposable
{
  void Dispose()
  {
     if(m_FontCreator != null)
          m_FontCreator.Dispose();
  }
}

then use TheConsumer class like so

using(TheConsumer consumer = new TheConsumer(....))
{
  ....
}

Answer 1: Avoid it. Don t keep objectsthat contain unmanaged resources around any longer than necessary.

Answer 2: If you do need the embedded fields as shown in your code, than both the FontCreator and the Consumer class need to implement IDisposable. But not a destructor (Finalizer).
The main argument for this is that FontCreator is the owner of the Font and should therefore take responsibility. And the Consumer is responsible for the Creator in the same way.

As others have noted, it appears you can at least avoid the m_FontCreator field in the Consumer class. But it depends on the rest of the code, is m_FontCreator used elsewhere?





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签