【. NET deep breathing "cleanup object references, one problem is easy to ignore

Source: Internet
Author: User

As you know, one of the important features of managed code is the automatic management of memory, which is what we often call garbage collection mechanism, those tall theories I will not repeat, interested friends can turn the book. I have a problem with this--I don't like to say something very serious about the theory, so I don't introduce it much.

In general, when the code executes beyond the valid range of a variable, or when an object instance is no longer referenced, the instance is refactored, the garbage collector is likely to clean up the portal, or it may not be cleaned up immediately, or it may be cleaned up later.

For some classes to customize for cleanup, we will take the following scenario:

1. Write the destructor and clean it in the destructor.

2, implement the IDisposable interface, and implement the Dispose method, write custom cleanup code in the method. When the type is instantiated, the Dispose method cleanup is called when it is finally no longer in use, and the type's destructor is called if it is cleaned up successfully. In general, how to implement the IDisposable interface, you do not have to write a destructor. If you want the Dispose method to be called automatically, you can wrap the code in the instantiated object in a using statement block, and the Dispose method is called automatically when the using block is finished executing.

Maybe someone laughed, old week, you are too funny, these basic knowledge who do not know? Of course, I said the above was meant to go around a small circle in order to get into the subject. So, I have a question: Is there some scenario where an object instance might not be recycled? Even if you call the Dispose method, even if you set the variable to NULL to dereference, even if you invoke the GC class method to reclaim ...

After the old weeks of testing, there is a real situation, and many friends are likely to ignore, and even in the awareness of the perception that the object instances have been recycled, and actually not recycled.

Let me briefly say the situation:

For example, there is a static class (static class members must be Static) A, which has static events. The static event of Class A is then handled in an instance of another class, and the method that handles the event is located on the instance object ...

No hurry, let's look at the real example. If I define a static class Mychecker, it has a static event checkevent.

     Public Static classMychecker {#regionStatic events Public Static EventEventHandler checkevent; #endregion         Public Static voidcallevent () {if(Checkevent! =NULL) {checkevent (New Object(), eventargs.empty); }        }    }

The Checkevent event is raised as long as the CallEvent method is called.

Then, define another class SampleClass, and in that class, handle the static events in the Mychecker just now.

    classsampleclass:idisposable { PublicSampleClass () {mychecker.checkevent+=mychecker_checkevent; }        voidMychecker_checkevent (Objectsender, EventArgs e) {            NewForm2 ().        Show (); }        ~SampleClass () {System.Diagnostics.Debug.WriteLine ("\ n See, the destructor is called. \ n"); }         Public voidDispose () {//...        }    }


In the constructor of the class, the handling of the Checkevent event is appended with the processing method named Mychecker_checkevent.

It may have been found that the old week of the SampleClass class A bit scary breath, both implemented the Dispose method, how to write the destructor, I write the destructor here is to verify that the class instance is really cleaned up, if the instance is really recycled, then the Debug class will be in the "output" The output prompt in the window shows that if there is no prompt output, the instance of the class is also hogging the memory.

Next Test.

            New SampleClass ();             await Task.delay (+);            Sc. Dispose ();             NULL ;            Gc. Collect ();


After instantiating SampleClass, then delay pauses for 10 seconds, 10 seconds later calls the Dispose method, and sets the variable to a null reference, which I fear cannot be cleaned up in time, and even the Gc.collect method is used.

While waiting for this 10-second period, you can call the static class's CallEvent method to raise the static event checkevent.

Mychecker.callevent ();

According to general understanding, after 10 seconds, the SampleClass instance should be cleaned up, and a hint will be output in the Output window.

OK, try it now.

......

The experimental results show that there is no output of the duck hairs in the Output window, which indicates that the SampleClass instance does not have a destructor at all after 10 seconds. And then something went wrong, what's going on? SampleClass instance does not have a reference, how does the destructor not occur?

In fact, we overlook a point: static event checkevent is also bound to the method of the SampleClass instance, in essence, although the variable is set to NULL, but the mychecker_ in the SampleClass instance The Checkevent method is also referenced by static events in static classes , so it is not recycled. I don't know if you understand.

This problem many friends in the actual development will be ignored, but also proudly think that the sample instance is really recycled, in fact, the instance will not be recycled, unless the program ends. Because Mychecker is a static class, it is not based on an instance. If Mychecker is not a static class, the SampleClass instance can be freed when the Mychecker instance is freed.

So, how to solve it? It is simple to unbind a static event from a method in the Dispose method of the SampleClass class, so that the static event no longer references the method member in the instance, and the instance can be refactored.

         Public void Dispose ()        {            -= mychecker_checkevent;        }

This example study tells us that you must be careful when dealing with static events in class instances .

Source code download for this sample: Http://files.cnblogs.com/files/tcjiaan/refsample.zip

All right, let's get this out of here today.

【. NET deep breathing "cleanup object references, one problem is easy to ignore

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.