Partilhar via


Windows 7 API Code Pack for .NET Framework: DX Types are disposable; explanation. #Win7 #CodePack #vs

@SlimDX asked on twitter last week:

Dear Windows API Code Pack: I may be mistaken, but your DX types aren't actually disposable from what I saw. What?

 

Here is a response from a developer on the Code Pack project:

 

Yes, we do support Dispose() on all of our wrapper types.

At first glance it might not be very obvious how we support it, but here's how:

C++/CLI generates the IDisposable pattern supporting method, Dispose(),.if we implement the equivalent ~ (destructor) on a ref class or struct, which we sometimes do. However, in most cases, I don't have an explicit destructor, instead for almost all ref classes and ref structs , Either I include an auto pointer member by value which implements a finalizer and destructor (desctructor calling into the finalizer code), or inherit from a class that includes that auto pointer.

Then, C++/CLI has this "helpful" feature that it will automatically implement the IDisposable required Dispose() method for us when a type contains an IDisposable member. Meaning, almost all of our exposed types (including all wrapper structs/classes), implement Dispose().

There are two easy ways to use Dispose() in C#:

- Call obj.Dispose() directly, when the obj is no longer needed (Preferably setting it to null afterwards to make sure it's no longer needed), e:.g

Viewport vp = new Viewport();

// Use vp here

...

vp.Dispose(); // vp destroyed

vp = null;

- Or, use the using(...) keyword, e.g (from one of our samples)

using (Texture2D buffer = swapChain.GetBuffer<Texture2D>(0))

{

renderTargetView = device.CreateRenderTargetView(buffer, null);

} // buffer.Dispose() will be called here

One look at the reflected code, or our docs, or by using intellisense on a type, will show we implement the Dispose() pattern.

e.g. of reflected code:

public class PassDescription : IDisposable

{

public PassDescription();

...

public override sealed void Dispose();

protected virtual void Dispose(bool __p1);

...

}

// Summary:

// Base class for all classes supporting internal IUnknown interfaces

public abstract class DirectUnknown : IDisposable

{

...

public override sealed void Dispose();

protected virtual void Dispose(bool __p1);

...

}

Comments