Domanda

I'm wrapping some native code that has some manual resource handling. I want my C# wrapper to handle this without passing the responsibility on to the clients. Is this possible, or will I inevitably have to implement IDisposable and pass on the responsibility to client code?

ie Is it possible to even write classes that handle managed resources automatically?

What if I say that deterministic handling of these resources is not a concern, and that I'm only concerned that they are released safely; I'm happy to let the GC schedule their release via finalizers.

È stato utile?

Soluzione

This is explicitly what a finalizer is designed to do. Write one to release the unmanaged resource, the CLR will automatically call it after the object got garbage collected. You can certainly implement IDisposable to get it released early but it is not a requirement. And can be skipped if the resource allocation is not impactful. The kind you describe matches that of a COM object. Whose .NET wrapper doesn't implement IDisposable either.

Keep an eye on basic resource usage of your program to ensure that this isn't a problem. It can be hard to judge if you don't enough about the actual resource that's being used.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top