简体   繁体   中英

C# Delete Instance of Class?

I am sort of new to C# and I have a quick question about instances of classes. I was told that using only "null"on an instance of a class isn't enough to delete an entire instance and all it's resources, such as pointers, etc. So I have: ClassHere myClass = new ClassHere() and myClass = null

I really must be thinking about this too hard... I'll give an example as to figure out how exactly the GC works.

Let's say we have 3 instances: x1, x2, x3. Each instance would be mapped to a variable: ClassHere myClass = new ClassHere() except you'd have x1, x2 and x3 instead of myClass.

Then say instances x2 and x3 make some sort of reference to x1. Let's say that x1 does nothing after being referenced by x2 and x3. The GC would only pick up x1 after x2's, and x3's references of x1 would be removed, correct?

If it picks it up even with those references. How would the GC know whether or not I actually need instance x1 which is referenced by x2 and x3 instead of deleting it?

Or am I missing something here?

Well, the only way to destroy a class is to remove it from your source tree :D You can, though destroy instances of a class.

Unlike C# doesn't have deterministic destructors. An object instance becomes eligible for garbage collection when the object instance becomes unreachable. That can happen by virtue of

  • all references to it being released (eg, variable going out of scope), or
  • all references to it being themselves unreachable (eg, the object instance is references in a collection, and the collection is itself unreachable.

When and if an object instance is garbage-collected depends on memory/resource pressure within the app domain (process). When the app domain ends, though, everything is garbage collected.

Usually you want to make things that matter implement IDisposable , so non-managed resources held can be deterministically released via using blocks and the like.

This is a simplistic answer, but the gist of it is: don't sweat it.

Any of your managed resources you don't need to worry about "deleting". The Garbage Collector will take care of this for you. You only need to worry about cleanup in the case where you are using unmanaged resources(Which I'm assuming you aren't as you don't mention it).

You do not need to null out variables for the GC to collect it.

Here's a link I found on a related stackoverflow question that might help: http://blogs.msdn.com/b/oldnewthing/archive/2010/08/10/10048149.aspx

If the code is running on a server GC isn't going to deallocate the object- unless you restart the server every half hour- seems like a legitimate question to me... I had a similar problem- detecting when a user shuts the browser as opposed to manually logging off the website- my solution was to create an instance for user with a timer and a flag that is set to true via ajax and reset to false by server side timer. But there was a potential for memory leaks- since there was no guarantee instance of the user was being deallocated when they would be automatically logged off.

So I create a class user outside webservice like this and instantiated a list of type user:

 class WebService{
  public static List<user> UserLoglist = new List<user>();//list of logged in users

 [WebMethod(Description = "Per session Hit Counter", EnableSession = true)]
public void  ClnUpdateFlag(string un)//gets called via ajax
{//Updates the flags i

    //update users status
    WebService.UserLoglist.Find(y => y.username == un).isLoggedin = true;
}
    }
public class user
{
    public string username;
    public System.Timers.Timer timScheduledTask = new System.Timers.Timer();
    public bool isLoggedin = true;
    public  user(string puser)
    {
        username = puser;

        setimer(); //set server side timer
    }
    void Timer1_Tick(object sender, EventArgs e)
   {

     ...
  if (isLoggedin)// window is still open
          isLoggedin = false;
   else// user closed the window
      {
         ...

          WebService.UserLoglist.RemoveAll(x => x.username == username);// instance is deleted here

   ...

      } 
      }
    }

    void setimer()
    {
        timScheduledTask.Interval = 3000;
        timScheduledTask.Enabled = true;
         timScheduledTask.Start(); 
        timScheduledTask.Elapsed +=
        new System.Timers.ElapsedEventHandler(Timer1_Tick);
    }
 }

}

    class login{

   ...
    public void Logon_Click(object sender, EventArgs e)
{
    if (Membership.ValidateUser(UserEmail.Text, UserPass.Text)){
        ...
         WebService.UserLoglist.Add(new user(UserEmail.Text));// instance of the user is instantiated here
        }
   ...
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM