0

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.

Tom Davies
  • 2,386
  • 3
  • 27
  • 44
  • 1
    This entirely depends on the unmanaged code in question. – Security Hound Jan 22 '13 at 16:15
  • The unmanaged resources are handles to opaque structures used within a dll. The dll api provides functions to create, increase the ref count, and release (decrease the ref count) of these handles. Any calls to the create/addref functions need to be matched to a corresponding release. – Tom Davies Jan 22 '13 at 16:24
  • Alright? You asked if its possible to write classes to handle the managed resources automatically. the answer of course is to use the garbage collector within .NET – Security Hound Jan 22 '13 at 16:29
  • I think you answered your own question, do it via finalizers if you want the GC to control it. – jlew Jan 22 '13 at 16:36
  • I've just read SO much about how any class holding managed resources should implement IDisposable, that's why I asked. – Tom Davies Jan 22 '13 at 17:02

1 Answers1

1

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536