How to manage / release / finalize unmanaged resources when the overall value goes out of scope

I have a type that encapsulates a key to an external resource. After the key is lost (all values ​​that share it are outside the scope), the resource must be released (implicitly) to the next garbage collection, as memory for regular values.

So, I'm looking for something similar to deleting OOP, or ForeignPtrjust that I present links to something other than objects from (although if it ForeignPtrcan work correctly and elegantly for this, knowing how to answer this question) .

Is it possible? if so, how?

+4
source share
2 answers

You can use System.Mem.Weak.addFinalizerfor this.

Unfortunately, the semantics for weak links can be a little difficult to understand at first. A warning note is especially important.

If you can attach IORef, MVaror TVarto your key and make a weak link / finalizer with it, it will probably be much more reliable.

In the special case, when your key is a pointer to unmanaged memory (for example, some C data structure), you must create ForeignPtrand attach a finalizer to it. The semantics for these finalizers are slightly different; rather than an arbitrary I / O action, the finalizer should be a pointer to an external function.

+4
source

ResourceT:

ResourceT - , , .

+5

All Articles