开发者

using in defining object in c#

when we use using for defining an object?for example:

       using (Login ob开发者_如何学GojLogin = new Login())

i know that we use when we want to clean the memory after using this object but i dont know when should we clean the memory.


The using statement should be used to timely dispose of objects which implement IDisposable. This does not actually clean managed memory but allows a managed object to release any unmanaged resources it may be holding and in some occasions remove references to managed objects to prevent memory leaks.

I suggest reading up on the following sites which provide in depth explanations of both IDisposable and the using statement

  • IDisposable, Finalizers and the definition of an unmanaged resource
  • http://www.codeproject.com/KB/dotnet/IDisposable.aspx


Whenever an object is disposable (it implements IDisposable interface) it means that it probably uses some unmanaged resources that can not be managed by garbage collector and therefore if your object is collected these resources might remain in the memory causing some problems. The solution for this problem is :

1.To implement IDisposable interface in such kind of objects and to clear/close unmanaged resources in Dispose method (for example if you are using a disposable object inside your object it'd be better to have a Dispose method to call its dispose inside)

2.To call the Dispose method of disposable objects when they are not needed anymore but be careful cause reusing a disposed object can throw some exceptions. The using syntax that you mentioned is a short way of doing the same and it interprets this:

using(var obj=new myDisposableObject)
{
obj.Something();
}

into following :

 var obj=new myDisposableObject();
    try
    {
    obj.Something();
    }
    catch
    {
    throw;
    }
    finally
    {
    obj.Dispose();
    }

thus you can always be sure that whatever happens the Dispose method of your object is always called.


You don't clean the memory; the object implementing IDisposable will clean its unmanaged resources in its Dispose method (or at least, that's the implication that the class is making by implementing IDisposable), and .NET will clean the memory when the object is collected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜