开发者

Reg: Managed objects and native resources in .net

开发者 https://www.devze.com 2023-02-26 13:40 出处:网络
I have come across this line when i was reading about dispose method documentation in msdn. here. In the explanation give there is a line which says Use the Dispose method primarily on managed objec

I have come across this line when i was reading about dispose method documentation in msdn.

here. In the explanation give there is a line which says Use the Dispose method primarily on managed objects that use native resources and on COM objects that are exposed开发者_如何学运维 to the .NET Framework.

Can any one explain what are managed objects and where are they used and what are native resources with some examples.

Thanks in advance


When you write a Win32 application you are responsible for managing memory. If you allocate memory you are responsible for releasing it, otherwise your program will have memory leaks.

In a nutshell, the Common Language Runtime, that is a "program" that runs .NET applications, is responsible for managing memory for you. When you create an object:

var myInstance = new MyObject();

you are not responsible for destructing this object as well as the memory resources it consumes. When you create an object like above on any .NET program (C#, F#, VB.NET...) you are creating a managed object.

However, your object, even being a managed object, may directly manipulate memory and allocate unmanaged resources. C# has a scope called unsafe to allow low level memory manipulation. Beside, your program may interact with resources beyond .NET, like Windows Registry or creating and deleting temporary files during program execution. You see? .NET CLR cannot manage these resources for you. So it is your responsabilily to dispose then when your program is finished. That's why you should implement IDisposable.

If you want examples, take a look at what classes do implement IDisposable. SqlConnection is one of them. There are several.

0

精彩评论

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

关注公众号