Use of Finalize/Dispose method in C#

后端 未结 13 2055
轮回少年
轮回少年 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:28

    using(NoGateway objNoGateway = new NoGateway())
    

    is equivalent to

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

    A finalizer is called upon the GC destroying your object. This can be at a totally different time than when you leave your method. The Dispose of IDisposable is called immediately after you leave the using block. Hence the pattern is usually to use using to free ressources immediately after you don't need them anymore.

提交回复
热议问题