开发者

Should I call Dispose method on an Image get from the Clipboard in C#

In C#/.NET, the method Clipboard.GetData() returns an object from the Clipboard.

If the object returned implements the IDisposable interface (such as an instance of the class Image), is it my respon开发者_运维知识库sibility to call the Dispose method on it (or use the "using" construct)?

The documentation of GetData does not says anything particular, so I assume the Clipboard object properly disposes everything. But my assumptions might be wrong.


If I really wanted to be sure, I'd look into the GetData() function with .NET Reflector to see what it does. I'm guessing it creates a copy of the image in the application's memory. So propably you need to dispose of it. Even if you don't need to, multiple dispose calls don't hurt.


Questions like these are tricky. The general rule is that the owner of the IDisposable object is responsible for calling Dispose. When I see a method like GetData I immediately think that it's intended semantics are to transfer ownership of the IDisposable object from the callee to the caller. So, yes, I would assume that you are responsible. Now, on the other hand, if it were instead a property called Data I would then assume that ownership still belongs to the containing object because a property has the general semantics of providing access to a held instance. The problem is that API developers are often inconsistent in defining who the owner is and that is why I say questions like these are tricky. But, again, I think it is safe to assume that you should be calling Dispose in this case.


Dispose method is supposed to be done if you use some unmanaged resources (file handles, unmanaged memory, etc). In such cases you should implement IDisposable and release resources in Dispose method.

Since you use GetData which return native .NET Object, you don't have to call Dispose method.

An example is provided here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜