Use of Finalize/Dispose method in C#

后端 未结 13 2069
轮回少年
轮回少年 2020-11-21 23:20

C# 2008

I have been working on this for a while now, and I am still confused about the use of finalize and dispose methods in code. My questions are below:

13条回答
  •  难免孤独
    2020-11-21 23:50

    Some aspects of another answer are slightly incorrect for 2 reasons:

    First,

    using(NoGateway objNoGateway = new NoGateway())
    

    actually is equivalent to:

    try
    {
        NoGateway = new NoGateway();
    }
    finally
    {
        if(NoGateway != null)
        {
            NoGateway.Dispose();
        }
    }
    

    This may sound ridiculous since the 'new' operator should never return 'null' unless you have an OutOfMemory exception. But consider the following cases: 1. You call a FactoryClass that returns an IDisposable resource or 2. If you have a type that may or may not inherit from IDisposable depending on its implementation - remember that I've seen the IDisposable pattern implemented incorrectly many times at many clients where developers just add a Dispose() method without inheriting from IDisposable (bad, bad, bad). You could also have the case of an IDisposable resource being returned from a property or method (again bad, bad, bad - don't 'give away your IDisposable resources)

    using(IDisposable objNoGateway = new NoGateway() as IDisposable)
    {
        if (NoGateway != null)
        {
            ...
    

    If the 'as' operator returns null (or property or method returning the resource), and your code in the 'using' block protects against 'null', your code will not blow up when trying to call Dispose on a null object because of the 'built-in' null check.

    The second reason your reply is not accurate is because of the following stmt:

    A finalizer is called upon the GC destroying your object

    First, Finalization (as well as GC itself) is non-deterministic. THe CLR determines when it will call a finalizer. i.e. the developer/code has no idea. If the IDisposable pattern is implemented correctly (as I've posted above) and GC.SuppressFinalize() has been called, the the Finalizer will NOT be called. This is one of the big reasons to properly implement the pattern correctly. Since there is only 1 Finalizer thread per managed process, regardless of the number of logical processors, you can easily degrade performance by backing up or even hanging the Finalizer thread by forgetting to call GC.SuppressFinalize().

    I've posted a correct implementation of the Dispose Pattern on my blog: How to Properly Implement the Dispose Pattern

提交回复
热议问题