Bug 14988 - GC.Collect does not perform collection
Summary: GC.Collect does not perform collection
Status: RESOLVED NOT_REPRODUCIBLE
Alias: None
Product: iOS
Classification: Xamarin
Component: XI runtime ()
Version: 7.0.0.x
Hardware: PC Mac OS
: --- normal
Target Milestone: Untriaged
Assignee: Bugzilla
URL:
Depends on:
Blocks:
 
Reported: 2013-09-25 12:37 UTC by Val Savvateev
Modified: 2013-09-25 19:38 UTC (History)
2 users (show)

Tags:
Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on Developer Community or GitHub with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
RESOLVED NOT_REPRODUCIBLE

Description Val Savvateev 2013-09-25 12:37:37 UTC
Consider the example:

class B
{
	~B()
	{
		Console.Write("Dying");
	}
}

public static void M(string[] args)
{
	var w1 = new WeakReference(new object());
	var w2 = new WeakReference(new B());
	var b = new B();
	b = null;

	GC.Collect();
	GC.WaitForPendingFinalizers(); // perhaps redundant
	Console.WriteLine("{0}", w1.IsAlive);
	Console.WriteLine("{0}", w2.IsAlive);
}

The output is:
True
True

I would expect and the two weak references NOT to be alive (i.e. the objects they reference be collected). Also, collection never happens for the object that was stored in variable "b" (the class B finalizer is never called)
Comment 1 Rolf Bjarne Kvinge [MSFT] 2013-09-25 19:38:43 UTC
The JIT will eliminate the line "b = null;" because it's redundant. This means that the the 'b' reference will still be on the stack when GC.Collect is called.

Try something like this:
using System;
using System.Threading;

class B
{
    ~B()
    {
        Console.Write("Dying");
    }

static WeakReference w1;
static WeakReference w2;

public static void Main(string[] args)
{
   var t = new Thread (() =>
   {
   
    w1 = new WeakReference(new object());
    w2 = new WeakReference(new B());

    var b = new B();
    b = null;
  });
  t.Start ();
  t.Join ();

    GC.Collect();
    GC.WaitForPendingFinalizers(); // perhaps redundant
    Console.WriteLine("{0}", w1.IsAlive);
    Console.WriteLine("{0}", w2.IsAlive);
}

}