The right way to dispose a NativeWindow?

T

tomko

Hi,

What is the right way to dispose of a NativeWindow? I guess the
NativeWindow is managed code and will be cleared by the GC, but the
window handle it is holding is a native handle!

I'm using the standard dispose code:

NativeWindow nativeWindow;

protected void Dispose( bool disposing )
{
if( disposing )
{

// Here?

}

// Or here?

}

Where should I call the ReleaseHandle() method?
 
N

Nicholas Paldino [.NET/C# MVP]

tomko,

In reality, it doesn't really matter because:

a) The NativeWindow is private to your class here.

b) Your implementation of IDisposable should always be called, otherwise,
there is a misunderstanding of how your class should be used (the
recommended implementation of IDisposable is nothing more than a stop-gap
for those that are not monitoring the lifetimes of objects correctly, when
they need to).

c) Because of a) and b), you will always have Dispose called, disposing will
always be true, so it doesn't matter if it is in the conditional block, or
after.

In the end, I would say take your pick.
 
B

Ben Voigt [C++ MVP]

tomko said:
Hi,

What is the right way to dispose of a NativeWindow? I guess the
NativeWindow is managed code and will be cleared by the GC, but the
window handle it is holding is a native handle!

I'm using the standard dispose code:

NativeWindow nativeWindow;

protected void Dispose( bool disposing )
{
if( disposing )
{

// Here?

}

// Or here?

}

Where should I call the ReleaseHandle() method?

Outside the conditional block. The rule is that managed resources should be
disposed only if disposing is true, and unmanaged resources should be freed
always. It's a good idea to zero or mark the stored handle to the unmanaged
resource to avoid a double free. ReleaseHandle already does that.

Make sure you understand the different between DestroyHandle and
ReleaseHandle and use the right one.
 
T

tomko

Outside the conditional block. The rule is that managed resources should be
disposed only if disposing is true, and unmanaged resources should be freed
always. It's a good idea to zero or mark the stored handle to the unmanaged
resource to avoid a double free. ReleaseHandle already does that.

Make sure you understand the different between DestroyHandle and
ReleaseHandle and use the right one.- Hide quoted text -

- Show quoted text -

But here the NativeWindow is a managed .NET object (right?) and the
handle it is holding is unmanaged. Can I safely makes calls to the
NativeHandle object or is there a risk of null pointer exception?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top