开发者

Odd Constructor

What does ~ do. This is an Asp.Net v2 class I have just inherited. Class works OK Theres a default constructor under it is ~VNC What is ~ used for ?

using System;
using System.Web;
using System.Data;
using System.Web.Services;
using System.Web.Services.P开发者_Python百科rotocols;
using System.Data.SqlClient;
using System.Configuration;

namespace UtopianClasses
{
    public class VNC
    {
        public VNC(){ }

        ~VNC() {
             GC.Collect();
        }

        public String VNCViewFilesLocationMCR
        {
            get {
              return  ConfigurationManager.AppSettings["VNCViewFilesLocation"].ToString();    
            }

... Rest of Class


As already mentioned, it's a destructor. However, not only should you probably not be explicitly implementing a destructor, you really should not be forcing a GC collection from inside a destructor, because the destructor is invoked by the garbage collector itself. As near as I can tell, that's a code smell in any GCed language.


This is a destructor, not a constructor. They are typically used to release native resources or handles in classes that wrap native APIs.

That being said, adding a constructor that calls GC.Collect() is a bad idea. The destructor is only called during finalization, so the garbage collector is already cleaning up this object, and any object this object referenced. There is no reason to do this, as it just adds overhead, and will actually slow down the system.

This was probably written by somebody with a C++ background who did not understand the intricacies of memory management in .NET. I would recommend removing this altogether.


They're actually called Finalizers in .net. They're called when the GC cleans up that object.

http://msdn.microsoft.com/en-us/library/system.object.finalize(VS.71).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜