本文介绍了确定托管VS非托管资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有许多关于管理VS非托管资源的问题。我理解这两者的基本定义。不过,我有一个很难知道当资源或对象的托管或非托管。

当我觉得非托管资源,我倾向于认为本土code不直接.NET的一部分,如的PInvoke或编组资源。我通常会认为意在界面的东西,将使用硬件如文件句柄或网络连接也被非托管资源。

什么是包本机非托管资源,如的FileStream

.NET对象

A 的FileStream 必须使用非托管资源,但是当我实施的IDisposable 模式,我认为这是一个管理还是非托管资源?

我一直在假设到目前为止,如果对象实现的IDisposable ,则管理。我怎么会知道,的IntPtr 应该被看作为一个非托管resoruce?

解决方案

时,FileStream是管理资源

管理资源是包含(和管理)非托管资源类。通常情况下,实际资源几层了。

正确的。

这是你从了它的价值的API的文档。但注意,在实践中,大多数程序员永远不会直接处理非托管资源。当你这样做有必要,使用的SafeHandle 类转向非托管资源到管理的资源。

There are lots of questions about managed vs unmanaged resources. I understand the basic definition of the two. However, I have a hard time knowing when a resource or object is managed or unmanaged.

When I think of unmanaged resources I tend to think of native code that isn't directly part of .NET such as pinvoke or marshaling resources. I would normally think of resources meant to interface to something that will use HW such as a file handle or network connection also being unmanaged.

What about .NET objects that wrap native unmanaged resources such as a FileStream.

A FileStream must use unmanaged resources, but when I implement the IDisposable pattern, should I consider this a managed or unmanaged resources?

I've been assuming thus far that if the object implements IDisposable, then it is managed. How would I know that IntPtr should be handled as an unmanaged resoruce?

解决方案

A FileStream is a managed resource.

Managed resources are classes that contain (and manage) unmanaged resources. Usually the actual resources are several layers down.

Correct.

From the documentation of the API that you got its value from. But do note that in practice, most programmers never deal with unmanaged resources directly. And when you do have to, use the SafeHandle class to turn an unmanaged resource into a managed resource.

这篇关于确定托管VS非托管资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 09:33
查看更多