Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Static destructor?

Status
Not open for further replies.

Hexonx

Programmer
Jan 10, 2001
102
US
My class contains an unmanaged system object member (a user profile handle) that is initialized in the static constructor. Conversely, I need to free the object when the class (not object instances) is destroyed, but I've never heard of a static destructor.

Perhaps I could use Environment.HasShutdownStarted in the finalizer, but all instances could have already been gc'd when the AppDomain unloads and the code wouldn't run.

Perhaps I could use the AppDomain.Unload event to run my code.

Any thoughts?
 
If you initialize the HANDLE in the constructor then you have to free or close it in the Destructor.
The solution is the following:
~ AnyClass()
{
// Close handle here.
}
You have NOT to call the destructor.
There is no control on when the destructor is called because this is determined by the garbage collector.

-obislavu-

 
obislavu,

Thanks for the reply. I understand the non-deterministic nature of garbage collection in .NET. True, resources initialized in the constructor need to be released in the destructor (unmanaged resources), but what about resources initialized in the static constructor? If they are released when the first instance is gc'd, all other active instances will also be impacted. This is what I'm trying to avoid.

What I've done so far is to wrap the unmanaged resource inside a class, hold a static instance of the wrapper class, but not explicitly dispose of it. The wrapper class disposes of the resource in its destructor. It's something like a singleton.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top