How can I deterministically dispose of a managed C++/CLI object from C#?

Deadly 提交于 2019-12-04 00:55:18

The C++/CLI destructor-like syntax automatically implements IDisposable, but it does so in a manner similar to C#'s explicit interface implementation. This means you'll have to cast to IDisposable to access the Dispose method:

((IDisposable)obj).Dispose();

It is not so obvious in C++/CLI but it works exactly the way it does in C#. You can see it when you look at the class with Object Browser. Or a decompiler like ildasm.exe, best way to see what it does.

When you write the destructor then the C++/CLI compiler auto-generates a bunch of code. It implements the disposable pattern, your class automatically implements IDisposable, even though you didn't declare it that way. And you get a public Dispose() method, a protected Dispose(bool) method and an automatic call to GC::SuppressFinalize().

You use delete in C++/CLI to explicitly invoke it, the compiler emits a Dispose() call. And you get the equivalent of RAII in C++/CLI by using stack semantics, the compiler automatically emits the Dispose call at the end of the scope block. Syntax and behavior that's familiar to C++ programmers.

You do the exact same thing you'd do in C# if the class would have been written in C#. You call Dispose() to invoke explicitly, you use the using statement to invoke it implicitly in an exception-safe way.

Same rules apply otherwise, you only need the destructor when you need to release something that is not managed memory. Almost always a native object, the one you allocated in the constructor. Consider that it might not be worth the bother if that unmanaged object is small and that GC::AddMemoryPressure() is a very decent alternative. You do however have to implement the finalizer (!ClassName()) in such a wrapper class. You cannot force external client code to call Dispose(), doing so is optional and it is often forgotten. You don't want such an oversight to cause an unmanaged memory leak, the finalizer ensures that it is still released. Usually the simplest way to write the destructor is to explicitly call the finalizer (this->!ClassName();)

You can't. At least, not from C#. Let the garbage collector do its job.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!