Dealing with .NET IDisposable objects

霸气de小男生 提交于 2019-12-02 15:29:32
Marc Gravell

FxCop might help (although it didn't spot a test I just fired at it); but yes: you are meant to check. IDisposable is simply such an important part of the system that you need to get into this habit. Using intellisense to look for .D is a good start (though not perfect).

However, it doesn't take long to familiarize yourself with types that need disposal; generally anything involving anything external (connection, file, database), for example.

ReSharper does the job too, offering a "put into using construct" option. It doesn't offer it as an error, though...

Of course, if you are unsure - try using it: the compiler will laugh mockingly at you if you are being paranoid:

using (int i = 5) {}

Error   1   'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'    

If an object implements the IDisposable interface, then it is for a reason and you are meant to call it and it shouldn't be viewed as optional. The easiest way to do that is to use a using block.

Dispose() is not intended to only be called by an object's finalizer and, in fact, many objects will implement Dispose() but no finalizer (which is perfectly valid).

The whole idea behind the dispose pattern is that you are providing a somewhat deterministic way to release the unmanaged resources maintained by the object (or any object in it's inheritance chain). By not calling Dispose() properly you absolutely can run in to a memory leak (or any number of other issues).

The Dispose() method is not in any way related to a destructor. The closest you get to a destructor in .NET is a finalizer. The using statement doesn't do any deallocation...in fact calling Dispose() doesn't do any deallocation on the managed heap; it only releases unmanaged resources that had been allocated. The managed resources aren't truely deallocated until the GC runs and collects the memory space allocated to that object graph.

The best ways to determine if a class implements IDisposable are:

  • IntelliSense (if it has a Dispose() or a Close() method)
  • MSDN
  • Reflector
  • Compiler (if it doesn't implement IDisposable you get a compiler error)
  • Common sense (if it feels like you should close/release the object after you're done, then you probably should)
  • Semantics (if there is an Open(), there is probably a corresponding Close() that should be called)
  • The compiler. Try placing it in a using statement. If it doesn't implement IDisposable, the compiler will generate an error.

Think of the dispose pattern as being all about scope lifetime management. You want to acquire the resource as last as possible, use as quickly as possibly, and release as soon as possible. The using statement helps to do this by ensuring that a call to Dispose() will be made even if there are exceptions.

Motti

This is why (IMHO) C++'s RAII is superior to .NET's using statement.

A lot of people said that IDisposable is only for un-managed resources, this is only true depending on how you define "resource". You can have a Read/Write lock implementing IDisposable and then the "resource" is the conceptual access to the code block. You can have an object that changes the cursor to hour-glass in the constructor and back to the previously saved value in IDispose and then the "resource" is the changed cursor. I would say that you use IDisposable when you want deterministic action to take place when leaving the scope no matter how the scope is left, but I have to admit that it's far less catchy than saying "it's for managing un-managed resource management".

See also the question about why there's no RAII in .NET.

GrahamS

In short, it's not the end of the world if I miss a using. I just wish something would generate at least a warning for it.

The problem here is that you can't always deal with an IDisposable by just wrapping it up in a using block. Sometimes you need the object to hang around for a bit longer. In which case you will have to call its Dispose method explicitly yourself.

A good example of this is where a class uses a private EventWaitHandle (or an AutoResetEvent) to communicate between two threads and you want to Dispose of the WaitHandle once the thread is finished.

So it isn't as simple as some tool just checking that you only create IDisposable objects within a using block.

@Atario, not only the accepted answer is wrong, your own edit is as well. Imagine the following situation (that actually occurred in one CTP of Visual Studio 2005):

For drawing graphics, you create pens without disposing them. Pens don't require a lot of memory but they use a GDI+ handle internally. If you don't dispose the pen, the GDI+ handle will not be released. If your application isn't memory intensive, quite some time can pass without the GC being called. However, the number of available GDI+ handles is restricted and soon enough, when you try to create a new pen, the operation will fail.

In fact, in Visual Studio 2005 CTP, if you used the application long enough, all fonts would suddenly switch to “System”.

This is precisely why it's not enough to rely on the GC for disposing. The memory usage doesn't necessarily corelate with the number of unmanaged resources that you acquire (and don't release). Therefore, these resoures may be exhausted long before the GC is called.

Additionally, there's of course the whole aspects of side-effects that these resources may have (such as access locks) that prevent other applications from working properly.

I don't really have anything to add to the general use of Using blocks but just wanted to add an exception to the rule:

Any object that implements IDisposable apparently should not throw an exception during its Dispose() method. This worked perfectly until WCF (there may be others), and it's now possible that an exception is thrown by a WCF channel during Dispose(). If this happens when it's used in a Using block, this causes issues, and requires the implementation of exception handling. This obviously requires more knowledge of the inner workings, which is why Microsoft now recommends not using WCF channels in Using blocks (sorry could not find link, but plenty other results in Google), even though it implements IDisposable.. Just to make things more complicated!

Unfortunately, neither FxCop or StyleCop seem to warn on this. As other commenters have mentioned, it is usually quite important to make sure to call dispose. If I'm not sure, I always check the Object Browser (Ctrl+Alt+J) to look at the inheritance tree.

I use using blocks primarily for this scenario:

I'm consuming some external object (usually an IDisposable wrapped COM object in my case). The state of the object itself may cause it to throw an exception or how it affects my code may cause me to throw an exception, and perhaps in many different places. In general, I trust no code outside of my current method to behave itself.

For the sake of argument, lets say I have 11 exit points to my method, 10 of which are inside this using block and 1 after it (which can be typical in some library code I've written).

Since the object is automatically disposed of when exiting the using block, I don't need to have 10 different .Dispose() calls--it just happens. This results in cleaner code, since it is now less cluttered with dispose calls (~10 fewer lines of code in this case).

There is also less risk of introducing IDisposable leak bugs (which can be time consuming to find) by somebody altering the code after me if they forget to call dispose, because it isn't necessary with a using block.

Like Fxcop (to which they're related), the code analysis tools in VS (if you have one of the higher-up editions) will find these cases too.

Always try to use the "using" blocks. For most objects, it doesn't make a big difference however I encountered a recent issue where I implemented an ActiveX control in a class and in didn't clean up gracefully unless the Dispose was called correctly. The bottom line is even if it doesn't seem to make much of a difference, try to do it correctly because some time it will make a difference.

scobi

According to this link the CodeRush add-in will detect and flag when local IDisposable variables aren't cleaned up, in real-time, as you type.

Could meet you halfway on your quest.

I'm not getting the point of your question. Thanks to the garbage collector, memory leaks are close to impossible to occur. However, you need some robust logic.

I use to create IDisposable classes like this:

public MyClass: IDisposable
{

    private bool _disposed = false;

    //Destructor
    ~MyClass()
    { Dispose(false); }

    public void Dispose()
    { Dispose(true); }

    private void Dispose(bool disposing)
    {
        if (_disposed) return;
        GC.SuppressFinalize(this);

        /* actions to always perform */

        if (disposing) { /* actions to be performed when Dispose() is called */ }

        _disposed=true;
}

Now, even if you miss to use using statement, the object will be eventually garbage-collected and proper destruction logic is executed. You may stop threads, end connections, save data, whatever you need (in this example, I unsubscribe from a remote service and perform a remote delete call if needed)

[Edit] obviously, calling Dispose as soon as possible helps application performance, and is a good practice. But, thanks to my example, if you forget to call Dispose it will be eventually called and the object is cleaned up.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!