I'm about to implement a managed wrapper class around an OpenGL texture and I want the object finalizer to call glDeleteTextures
.
So, the thread calling the finalizer (GC thread?) must be bound to the OpenGL rendering context in which the texture belongs by calling wglMakeCurrent
.
But the wglMakeCurrent
documentation clearly states that an OpenGL rendering context cannot be the current rendering context of multiple threads at the same time.
If GC can triggers at any time, I cannot guarantee that no other thread is using the context when it happens.
What is the proper way to call glDeleteTextures
in .net object's finalizer ?
Edit
This wrapper class will be used in a complex system of "loading on demand" scene graph, with caching strategy implemented by WeakReference
and such. So, "manual disposal" is not an option I want to consider: I really want the GC to handle that.
Ok, so here is what I've done.
I implemented the IDisposable
interface on my resource object (base class for texture, vertex array, shaders, etc).
When disposed (or finalized if not disposed manually), the resource add its id and type to a synchronized list owned by its OpenGL context wrapper class and eventually wake up the main thread by setting an event.
I've changed my application message pump (I now use MsgWaitForMultipleObjects
instead of GetMessage
) and in the loop, once acquired the OpenGL context, the thread first "free" unused resources before processing the message (if any).
It works like a charm so far.
Thanks to Stefan Hanke for hints on this one !