C#: Saving a delegate from garbage collection (static no option)

1.7k views Asked by At

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.

2

There are 2 answers

1
decyclone On BEST ANSWER

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.

1
Cheng Chen On

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.