Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

destructor - Manually destroy C# objects

I am fairly new to learning C# (from Java & C++ background) and I have a question about manual garbage disposal: is it even possible to manually destroy an object in C#? I know about the IDisposable interface, but suppose I'm dealing with a class which I didn't write and it doesn't implement it? It wouldn't have a .Dispose() method, so that and using { } is out, and .Finalize is always either protected or private so that's not an option either.

(I am just trying to learn what is possible in C# in this case. I suppose if all else fails I could inherit the hypothetical ImNotDisposable class so that it does implement IDisposable.)

question from:https://stackoverflow.com/questions/1987251/manually-destroy-c-sharp-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't manually destroy .Net objects. That's what being a managed environment is all about.

In fact, if the object is actually reachable, meaning you have a reference you can use to tell the GC which object you want to destroy, collecting that object will be impossible. The GC will never collect any object that's still reachable.

What you can do is call GC.Collect() to force a general collection. However, this almost never a good idea.

Instead, it's probably better to simply pretend any object that doesn't use unmanaged resources and is not reachable by any other object in your program is immediately destroyed. I know this doesn't happen, but at this point the object is just a block of memory like any other; you can't reclaim it and it will eventually be collected, so it may just as well be dead to you.

One final note about IDisposable. You should only use it for types that wrap unmanaged resources: things like sockets, database connections, gdi objects, etc, and the occasional event/delegate subscription.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...