1
public Dictionary<string, IMYObject> MYObjectContainer
{
    get
    {
        if (Session["MYObjectPool"] == null)
            Session["MYObjectPool"] = new Dictionary<string,IMYObject>();
        return (Dictionary<string, IMYObject>)Session["MYObjectPool"];
    }
    set
    {
        Session["MYObjectPool"] = value;
    }
}

public ActionResult Close()
{
    try
    {
        MyObject obj = this.MYObjectContainer["Key"] 
        this.MYObjectContainer = null;             
        return Json(new { success = true }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception Ex)
    {
        throw X
    }
}

The garbage collector will delete when the object has no valid referee Here there are two referee,

1.obj (Local variable)

2.Session

First I made the session referee invalid by setting this.MYObjectContainer = null; Second when the function ends the obj will be popped out of stack thus second referee is invalid

Does this makes the MYObjectContainer eligible for Garbage Collector to be Cleared ?

Please ignore if my question is totally wrong please advice me ?

How Garbage Collector works in ASP.NET Session ?

Kjensen
  • 12,447
  • 36
  • 109
  • 171
Krishjs
  • 358
  • 2
  • 17
  • The garbage collector will destroy the session as an indirect consequence of the session timing out. My advice is not to worry about garbage collection with respect to this. – krisdyson Sep 24 '14 at 06:59
  • On Log out if I use Session.Abandon() will this also make the garbage collector to destroy session immediately. – Krishjs Sep 24 '14 at 07:34
  • `The garbage collector will delete when the object has no valid refere` - this is false. Have you [read the documentation on garbage collection on .NET](http://msdn.microsoft.com/en-us/library/0xy59wtx%28v=vs.110%29.aspx)? – Aaronaught Dec 26 '14 at 21:09
  • Could say the fact that makes it false ? – Krishjs Jan 07 '15 at 09:55

1 Answers1

2

In your example above the Session object will not be garbage collected until the session times out.

You'll have to decide if this is your wanted behavior or not :) - Will you need the object later?

If you want to remove the object from Session you'll also have to write Session["MYObjectPool"] = null or Session.Remove("MYObjectPool") (which will do the same)

Many times having objects laying around in Session is not a problem, but if the objects are large (e.g. megabytes or even gigabytes) and/or you have lots of users (all of who will get their own session) or many sites on the same server having objects laying around will be a problem.

Session is handy, but you have to realize its limitations...

mortb
  • 9,361
  • 3
  • 26
  • 44