开发者

Do native method reference have to be disposed - and if so are there any recommended practices to do so

I have a class which uses a method in user32.dll:

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr windowHandlerPtr);

According to Effective C#, should all classes which uses unmanaged code implement both IDisposable and a开发者_Go百科 finalizer. Without going into the details in that discussion, is there a need to dispose this kind of extern method declaration? If so - how would that dispose method look like?


That's not really a "reference", but instead a declaration. It doesn't actually create anything, so no need to dispose (nothing to dispose, in fact).

Using a return value from unmanaged code is something you should watch, though - in this case it's just a bool that you don't need to worry about. But in most cases you should look at the unmanaged API's documentation to see if it should be released somehow. If it is, then wrap that up in a class that you can dispose of properly. Here's a decent article on IDisposable

A rule of thumb is: If it implements IDisposable always dispose of it, and if it's an unmanaged resource, make sure it is properly released.


In this case, IntPtr has no unmanaged resource to be disposed of. Return value is bool also so in the same way nothing to do. However, it could be important how you get hold of IntPtr, if you create it (e.g. createDC), you need to release it (by calling another unmanaged method) but in this case you just get the value and then pass it.


According to Effective C#, should all classes which uses unmanaged code implement both IDisposable and a finalizer.

No, this is about using unmanaged resources, not code. In Windows, resources are almost invariably represented by 'handles'. Unmanaged code in itself is not a resource, there is no kernel object associated with it beyond the handle for the DLL, a handle you don't have access to.

The argument you pass to SetForegroundWindow is indeed one of those resources. It is a handle to a window. But you didn't create that window yourself, you're trying to set the focus to some window that was already created and is managed by other code. You should not dispose objects that you didn't create.

Notable too is that the advice is outdated. Windows handles should be wrapped by one of the SafeHandle derived classes. They already provide a finalizer, you shouldn't implement your own. Just implement Dispose() and call the SafeHandle.Dispose() method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜