Krishjs
Krishjs

Reputation: 368

How will the Garbage Collector handle a Session in ASP.NET MVC

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 ?

Upvotes: 2

Views: 2867

Answers (1)

mortb
mortb

Reputation: 9859

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...

Upvotes: 3

Related Questions