Question

I am currently using a static delegate in a wrapper class for a C dll to avoid that the delegate, which points to a unsafe function, gets garbaged collected.
This was working fine until I have now the requirement to support multiple instances of the class. A workaround might be to keep a list of the static delegates, but I would like to find a simpler solution.

Was it helpful?

Solution

To keep an object from being collected, you must maintain a reference to it.

Static members in static classes live for application lifetime.

For instance class members, depending on your class design and project design, you may take different approaches. Maintaining a static list may not be a bad idea.

My only question is how are you able to figure that the delegate is being collected. Because, if you are able to access it, then you must have maintained a reference of it. In which case, it must have stayed in memory.

OTHER TIPS

I think you made a mistake: Static variables lives in the whole life-cycle of the application, they will never be GCed when the app is running.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top