C# Dispose : when dispose and who dispose it

2019-05-21 10:11发布

问题:

I'm getting in nerve between dispose and finalize. Here is my example code:

public class Car:IDisposable
    {
        public string name;
        public Car()
        {
            name = "My Car";
        }
        public void Dispose()
        {
            Console.WriteLine("This object has been disposed");
        }
    }
public static void Main()
        {
            Car anotherCar;
            using (var car = new Car())
            {
                anotherCar = car;
                Console.WriteLine("Before dispose. Name is: "+anotherCar.name);
            }

            Console.WriteLine("After dispose. Name is: "+anotherCar.name);

        }

The result is:

Before dispose. Name is My Car
This object has been disposed
After dispose. Name is My Car

My question is : because C# will automatically dispose object after using{}, so I think at line "After dispose". anotherCar.name must be NULL. why it still be "My Car" ?

And my another question is : my book said that you shouldn't use GC.Collect() for some reason and one of these is Performance. So, who dispose object ? If that is Garbage Collector,too so I think dipose() has the same performance issues with finalizer()

Thanks :)

回答1:

I think you are misunderstanding what Dispose actually does. It doesn't destroy your object, set anything to null, or otherwise perform any sort of magic. When you use the using statement, that just guarantees that Dispose will be called. What you do in your Dispose method is what determines the behavior of your object. Not the language or .NET framework.



回答2:

If you look at the code again you will realize immediately that simply putting a Dispose() method on a class and implementing IDisposable does not add any behind the scenes magic, it is just a normal method with the added convenience that it will be called at the end of an using statement.

Generally in the Dispose method you should take care of clearing any (unmanaged) resources you want freed by yourself, for example closing a db connection or a file which was open for reading/saving...

Microsoft has a nice help page about implementing IDisposable correctly.



回答3:

An object in .net is generally a combination of a type reference and the public and private fields required by that type (there are a few special cases like arrays and strings). Once created, an object in .net will continue to exist as long as some form of reference to it exists. Once there are no longer any references to an object, if will effectively cease to exist; any memory it had occupied will simply be unused memory, eligible for reuse at the next garbage collection.

The purpose of Dispose is not to destroy an object, but rather to allow an object to perform necessary actions with things outside itself before it disappears. As a simple example, suppose an object asks a remote server to grant it exclusive access to a file; the server supplies a token, with a promise that access will only be granted to code supplying that token. If the object were to simply disappear, the external server would leave the file locked for the exclusive use of code that holds a token that no longer exists. In other words, the file would be forever(*) unusable by anyone. Adding a Dispose method to the object which asked for the token would allow the object to sent the server an "Okay--I'm done with file XYZ1493" message, thus making the file available to other entities.

Note that the Dispose method doesn't actually destroy the file object. It may prompt the object to erase some of the data stored in its fields, but the object will continue to exist as long as any reference to it exists, and will cease to exist thereafter. There are some cases where calling Dispose on an object may hasten the demise of the object itself, by asking other outside objects which hold references to it to destroy those references. Even in those cases, however, the purpose of Dispose is to allow objects to issue requests to other things.



标签: c# dispose