I want to know if IDisposable objects will dispose on session ending.
I know, I can dispose on Session ending event myself. But I want to write an IDisposable class.
For example, I have
public class MyObject : IDisposable
{
// some properties
public void Dispose()
{
// disposing
}
}
and I need to dispose this object on session ending time :
protected void Session_End(object sender, EventArgs e)
{
if (Session["key"] != null)
((MyObject)Session["key"]).Dispose();
}
So, I want to know on session ending time that operation will automatically or I need write as above.
Session_End does not automatically dispose of IDisposable objects, so your Session_End solution is correct.
However:
So try and find a solution that doesn't require you to store IDisposable objects in Session.
An instance of a class which implements the IDisposable
interface will only be "disposed" whenever you call the Dispose
method, whether directly or indirectly via the using
construct. It's not something which happens automatically whenever an object falls out of scope.
For example, this would be bad practice;
public void SomeMethodCalledDuringSession()
{
var resourceHog = new ResourceHog(); // where ResourceHog : IDisposable
// Perform operations
}
The object is never disposed properly here, regardless of your ASP.NET session ending. However, you can call Dispose
directly when you're finished, or a better idea is to do this;
public void SomeMethodCalledDuringSession()
{
using(var resourceHog = new ResourceHog()) // where ResourceHog : IDisposable
{
// Perform operations
}
}
This translates into a try ... finally
pattern, with the call to Dispose
in the finally
clause, ensuring that it gets called (apart from a few rare situations).
Edit : I would also read this; http://nitoprograms.blogspot.co.uk/2009/08/how-to-implement-idisposable-and.html
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.