Given the following:
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration);
Taking into account multi-threading and Garbage Collection modes, under what circumstances would you get a deadlock on WaitForPendingFinalizers
?
Note: I am not looking for answers about the reasons why you shouldn't be calling GC.Collect
.
There is famous deadlock on WaitForPendingFinalizers, described by Jeffrey Richter. It is shown here: http://haacked.com/archive/2005/04/12/neverlockthis.aspx
It is caused by incorrect using of lock(this). Anyway, this is situation when WaitForPendingFinalizers is locked.
You won't experience any kind of deadlock situation when calling
GC.Collect
andGC.WaitForPendingFinalizers
unless you are accessing managed objects within yourFinalize
methods. Calling methods of other objects with a public scope could potentially lead to unpredictable results, including a deadlock. The reason is that you're not in total control of those other objects' locking patterns. It could be locked by anyone while your finalizer method is trying to access it.Additionally, locking
this
explicitly in the finalizer is almost guaranteed to cause a deadlock, as LukeH's answer demonstrates. You can read Jeffrey Richter's original article on that here.In general, you should only be releasing unmanaged resources in your finalizers, which should alleviate any such concerns about deadlocks.