views:

62

answers:

2

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<object> from DB call 
           GC.Collect(2);
           GC.WaitForPendingFinalizers();
           GC.Collect(2);
}
+2  A: 

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.

Brian Rasmussen
Only if the snippet is in the finalizer!! Virtual -1 ....
Aliostad
I edited the snippet, I don't actually lock on "this" it was just added to keep the example as small as possible
jquery auth
@Aliostad: Thanks for leaving a comment instead of just down voting. If the code above runs on a user thread and acquires the lock and then waits for the finalizer to run. Then if the finalizer tries to lock on the same object, it will block as this is already held by the other thread.
Brian Rasmussen
awesome answer thanks
jquery auth
A: 

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.

Aliostad