Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Why "Finalize method should not reference any other objects"?

I have been pondering why it is recommended that we should not release managed resources inside finalize. If you see the code example at http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx , and search for string "Dispose(bool disposing) executes in two distinct scenarios" and read that comment, you will understand what I mean.

Only possibility I can think of is that it probably has something to do with the fact that it is not possible to predict when finalizer will get called. Does anyone know the right answer ?

thanks, mishal

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you're referencing another object from the finalizer, you don't know if that object has already been finalized - and how it will behave if it is finalized. (I don't know whether any current CLR runs multiple finalizer threads, but another scary possibility is that it's in the process of being finalized when your finalizer runs.)

All you should need to do in a finalizer is release unmanaged resources that you own directly. If you're referencing other managed types which own resources, let them do their job in their finalizers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...