Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 903263
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T15:50:52+00:00 2026-05-15T15:50:52+00:00

OK, I realize that question might seem weird, but I just noticed something that

  • 0

OK, I realize that question might seem weird, but I just noticed something that really puzzled me… Have a look at this code :

static void TestGC()
{
        object o1 = new Object();
        object o2 = new Object();
        WeakReference w1 = new WeakReference(o1);
        WeakReference w2 = new WeakReference(o2);

        GC.Collect();

        Console.WriteLine("o1 is alive: {0}", w1.IsAlive);
        Console.WriteLine("o2 is alive: {0}", w2.IsAlive);
}

Since o1 and o2 are still in scope when the garbage collection occurs, I would have expected the following output:

o1 is alive: True
o2 is alive: True

But instead, here’s what I got:

o1 is alive: False
o2 is alive: False

NOTE : this occurs only when the code is compiled in Release mode and run outside the debugger

My guess is that the GC detects that o1 and o2 won’t be used again before they go out of scope, and collects them early. To validate this hypothesis, I added the following line at the end of the TestGC method :

string s = o2.ToString();

And I got the following output :

o1 is alive: False
o2 is alive: True

So in that case, o2 isn’t collected.

Could someone shed some light on what’s going on ? Is this related to JIT optimizations ? What’s happening exactly ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T15:50:53+00:00Added an answer on May 15, 2026 at 3:50 pm

    The Garbage Collector relies on information compiled into your assembly provided by the JIT compiler that tells it what code address ranges various variables and “things” are still in use over.

    As such, in your code, since you no longer use the object variables GC is free to collect them. WeakReference will not prevent this, in fact, this is the whole point of a WR, to allow you to keep a reference to an object, while not preventing it from being collected.

    The case about WeakReference objects is nicely summed up in the one-line description on MSDN:

    Represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection.

    The WeakReference objects are not garbage collected, so you can safely use those, but the objects they refer to had only the WR reference left, and thus were free to collect.

    When executing code through the debugger, variables are artificially extended in scope to last until their scope ends, typically the end of the block they’re declared in (like methods), so that you can inspect them at a breakpoint.

    There’s some subtle things to discover with this. Consider the following code:

    using System;
    
    namespace ConsoleApplication20
    {
        public class Test
        {
            public int Value;
    
            ~Test()
            {
                Console.Out.WriteLine("Test collected");
            }
    
            public void Execute()
            {
                Console.Out.WriteLine("The value of Value: " + Value);
    
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
    
                Console.Out.WriteLine("Leaving Test.Execute");
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Test t = new Test { Value = 15 };
                t.Execute();
            }
        }
    }
    

    In Release-mode, executed without a debugger attached, here’s the output:

    The value of Value: 15
    Test collected
    Leaving Test.Execute
    

    The reason for this is that even though you’re still executing inside a method associated with the Test object, at the point of asking GC to do it’s thing, there is no need for any instance references to Test (no reference to this or Value), and no calls to any instance-method left to perform, so the object is safe to collect.

    This can have some nasty side-effects if you’re not aware of it.

    Consider the following class:

    public class ClassThatHoldsUnmanagedResource : IDisposable
    {
        private IntPtr _HandleToSomethingUnmanaged;
    
        public ClassThatHoldsUnmanagedResource()
        {
            _HandleToSomethingUnmanaged = (... open file, whatever);
        }
    
        ~ClassThatHoldsUnmanagedResource()
        {
            Dispose(false);
        }
    
        public void Dispose()
        {
            Dispose(true);
        }
    
        protected virtual void Dispose(bool disposing)
        {
            (release unmanaged resource here);
            ... rest of dispose
        }
    
        public void Test()
        {
            IntPtr local = _HandleToSomethingUnmanaged;
    
            // DANGER!
    
            ... access resource through local here
        }
    

    At this point, what if Test doesn’t use any instance-data after grabbing a copy of the unmanaged handle? What if GC now runs at the point where I wrote “DANGER”? Do you see where this is going? When GC runs, it will execute the finalizer, which will yank the access to the unmanaged resource out from under Test, which is still executing.

    Unmanaged resources, typically accessed through an IntPtr or similar, is opaque to the garbage collector, and it does not consider these when judging the life of an object.

    In other words, that we keep a reference to the handle in a local variable is meaningless to GC, it only notices that there are no instance-references left, and thus considers the object safe to collect.

    This if course assumes that there is no outside reference to the object that is still considered “alive”. For instance, if the above class was used from a method like this:

    public void DoSomething()
    {
        ClassThatHoldsUnmanagedResource = new ClassThatHoldsUnmanagedResource();
        ClassThatHoldsUnmanagedResource.Test();
    }
    

    Then you have the exact same problem.

    (of course, you probably shouldn’t be using it like this, since it implements IDisposable, you should be using a using-block or calling Dispose manually.)

    The correct way to write the above method is to enforce that GC won’t collect our object while we still need it:

    public void Test()
    {
        IntPtr local = _HandleToSomethingUnmanaged;
    
        ... access resource through local here
    
        GC.KeepAlive(this); // won't be collected before this has executed
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I realize that this question has been asked 100times but none that I have
I realize that this question might not make sense to some, but I was
I realize this might be an easy question that I may have overlooked in
I realize that this might be a duplicate question but this question is very
I realize that this question is impossible to answer absolutely, but I'm only after
While I realize that this question has been asked once or twice ago but
Ok so I realize that this is a pretty vague question, but bear with
I asked this question in the restkit google group, but realize now that it
I can't seem to find a question on this, but it might be because
I have posted this question on the Ext-GWT forums, I am just hoping that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.