Reputation: 67
Hi in the following stuff am trying to remove the session after completing the certain tasks. but the session.remove() not working here.
if (Session["CaseNumber"] != "" || Session["CaseNumber"] != null)
{
casenumber = Session["CaseNumber"].ToString();
guid = Session["guid"].ToString();
_duration = bal.viewServiceActivity(guid);
case1 = bal.viewCaseDetail(casenumber);
dt = bal.getRelatedNotes(guid);
Session.Remove("CaseNumber");
Session.Remove("guid");
}
else
{
casenumber = Session["searchCase"].ToString();
guid = Session["caseGuid"].ToString();
_duration = bal.viewServiceActivity(guid);
case1 = bal.viewCaseDetail(casenumber);
dt = bal.getRelatedNotes(guid);
Session.Remove("searchCase");
Session.Remove("caseGuid");
}
Upvotes: 1
Views: 2339
Reputation: 10565
There's nothing really wrong with portion of your code shown above. Just understanding is required about how it works.
Session.Remove(key)
removes memory used for the key in the session dictionary. When using second approach of : Session["searchCase"]=null;
, the key will still exist in the Session although the value is null.
Try setting the Session["Key_Name"]
to null
. For example:
if (Session["CaseNumber"] != "" || Session["CaseNumber"] != null)
{
casenumber = Session["CaseNumber"].ToString();
guid = Session["guid"].ToString();
_duration = bal.viewServiceActivity(guid);
case1 = bal.viewCaseDetail(casenumber);
dt = bal.getRelatedNotes(guid);
Session["CaseNumber"] = null; // Set NULL
Session["guid"] = null; // Set NULL
}
Session.Remove()
doesn't destroys the object bypassing all basic .net rules of object referencing and memory management. What you need to understand here is that Session.Remove()
does exactly what it suggests: It removes the reference to the object from its internal collection. Nothing more to expect.
If you need something destroyed, you need to implement IDisposable
, and furthermore, you may instruct the garbage collector to collect if you are in a hurry using GC.Collect()
.
Check this SO question: Proper use of the IDisposable interface
Microsoft Forum confirms the same.
It seems more like an optimization OR so called standard way of implementation.
When you remove an object it is 'marked for removal' but not really removed...unless space is required.
It's how garbage collection works. Just because an object goes out of scope doesn't mean it's destructor gets called and the memory freed immediately. May be GC
can remove an object much later.
Still, as a last check, do this :
Make sure you are not viewing a cached version of the page, or you don't add the item to the Session object again somewhere in your application.
Upvotes: 3