Garbage collection inside a lock object
Putting peoples opinions about garbage collection aside are there any deadlocking issues with the following:
private static readonly object lockObj = new object();
lock(lockObj )
{
///Load objects into a cache List<obje开发者_开发技巧ct> from DB call
GC.Collect(2);
GC.WaitForPendingFinalizers();
GC.Collect(2);
}
Major edit, so comments may seem out of place. Sorry for the inconvenience.
It is hard to tell for sure.
Assuming the code looks something like this
public class SomeType {
private static readonly object Lock = new object();
public void Foo() {
lock (Lock) {
Console.WriteLine("in foo");
GC.Collect(2);
GC.WaitForPendingFinalizers();
GC.Collect(2);
}
}
~SomeType() {
lock (Lock) {
Console.WriteLine("in finalizer");
}
}
}
You could get a deadlock if you had more instances of SomeType
as they all share a static object for locking. You need to have at least one unrooted and uncollected instance of SomeType
and call Foo
on another instance.
Now, if you don't have the finalizer as above, I can't see how the code could deadlock.
No possibility of a deadlock. But why locking this? Why the second GC.Collect()?
GC.WaitForPendingFinalizers() is a blocking code so won't return until done. So I am not sure what you achive by locking.
精彩评论