Use of Finalize/Dispose method in C#

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

    1. If you are using other managed objects that are using unmanaged resources, it is not your responsibility to ensure those are finalized. Your responsibility is to call Dispose on those objects when Dispose is called on your object, and it stops there.

    2. If your class doesn't use any scarce resources, I fail to see why you would make your class implement IDisposable. You should only do so if you're:

      • Know you will have scarce resources in your objects soon, just not now (and I mean that as in "we're still developing, it will be here before we're done", not as in "I think we'll need this")
      • Using scarce resources
    3. Yes, the code that uses your code must call the Dispose method of your object. And yes, the code that uses your object can use using as you've shown.

    4. (2 again?) It is likely that the WebClient uses either unmanaged resources, or other managed resources that implement IDisposable. The exact reason, however, is not important. What is important is that it implements IDisposable, and so it falls on you to act upon that knowledge by disposing of the object when you're done with it, even if it turns out WebClient uses no other resources at all.

提交回复
热议问题