Garbage collection inside the lock object

Assuming people's opinions on garbage collection, are there any deadlock problems 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);
}
+3
source share
2 answers

The main change, so comments may seem inappropriate. We apologize for the inconvenience.

Hard to say 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 can get a dead end if you had more instances SomeType, since they all use a static object to lock. You must have at least one uncovered and unsigned instance SomeTypeand call Fooin another instance.

, , , , .

+2

. ? GC.Collect()?

GC.WaitForPendingFinalizers() - , . , .

0

Source: https://habr.com/ru/post/1769309/


All Articles