Please avoid implement C# Destruction

來源:互聯網
上載者:User

I remember in the attach mail I gave my suggestions about how to use Destruction in C#, but it seems it didn’t catch your eyes.

So I would like to give my kindly suggestions and remind you again.

Before I debate with you,  please have a look at this article: Dispose & Finalize

Ø Tip from the author said:

· Don't create empty destructors. In other words, you should never explicitly define a destructor unless your class needs to clean up unmanaged resources—and if you do define one, it should do some work. If, later, you no longer need to clean up unmanaged resources in the destructor, remove it altogether”.

One more, in this article Finalization section,  Jeffrey Richter said:

· “let me warn you right now: object finalization and destructors have very different semantics and it is best to forget everything you know about destructors when thinking about finalization.”

· “When designing a type it is best to avoid using a Finalize method.”

He also listed many reasons to explain why we should avoid to use a Finalize method in that article.

So, Destruction in C# works total different with Destruction in C++.

And there are two formats misuse C# Destruction in our project, there are:

Format 1:

       ~DisplaySettingsListener()

       {

       }

Format 2:

       ~DisplaySettingsListener()

       {

            UnAdvise(); // un-register the events

        }

Format 1 is empty destructor which will has some performance issue. (The DisplaySettingsListener object requires at least two garbage collections, detail information please refer to MSDN from here.)

Format 2 try to un-register events in destructor,  but it never works as your expect. Why? The even bad news is that this format misuse of Destruction is one important killer who caused the document could not been disposed when we close the document in our product.

Seeing is believing,  let me show you a simple example to explain why the format 2 doesn’t make sense.

Code
 1    public class Program
 2    {
 3        static void Main(string[] args)
 4        {
 5            DisplayMemory();
 6            Console.WriteLine();
 7            for (int i = 0; i < 5; i++)
 8            {
 9                Console.WriteLine("--- New Listener #{0} ---", i + 1);
10                DisplaySettingsListener listener = new DisplaySettingsListener();
11                listener = null;
12
13                // Force the GC to collect
14                GC.Collect();
15                GC.WaitForPendingFinalizers();
16                GC.Collect();
17
18                DisplayMemory();
19            }
20            Console.ReadLine();
21        }
22
23        private static void DisplayMemory()
24        {
25            Console.WriteLine("Total memory: {0:###,###,###,##0} bytes", GC.GetTotalMemory(true));
26            Console.WriteLine();
27        }
28    }
29
30    class DisplaySettingsListener
31    {
32        byte[] m_ExtraMemory = new byte[1000000];
33
34        public DisplaySettingsListener()
35        {
36            SystemEvents.DisplaySettingsChanged += new EventHandler(DisplaySettingsChanged);
37        }
38      
39        ~DisplaySettingsListener()
40        {
41            Console.WriteLine("Destroying");
42            SystemEvents.DisplaySettingsChanged -= new EventHandler(DisplaySettingsChanged);
43        }
44
45        private void DisplaySettingsChanged(object sender, EventArgs e)
46        {
47        }
48    }

If you are interested on it, please copy the above code, and run it  on your computer.

What do you see? Shocked at it?

Shows the following figure from my side:

The results show that the byte array resource were NEVER collected, Un-register event in Destruction here doesn’t make sense at all.

So how to fix this problem?  In fact, I also have gave my solution in the attached mail, the key point is implement IDispose interface or implement Dispose Pattern, detail information please refer to this article.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.