?
Solved

Does garbage collection happen at the process level or appdomain level?

Posted on 2009-04-22
8
Medium Priority
?
1,377 Views
Last Modified: 2012-08-14
When garbage collection occurs, does it halt all app domains in a given process during the collection, or just a single app domain? Is this irrespective of all garbage collection parameters?

If one wants to separate two logical modules of code from trigger garbage collections on each other, is the only way to isolate them in two separate processes?

Thanks in advance, and please provide a reference source for your answer.
0
Comment
Question by:ebyrne
  • 4
  • 4
8 Comments
 
LVL 21

Expert Comment

by:MogalManic
ID: 24214917
Garbage collection happens on a separate thread.  When it occurs it will freeze all threads in the application domain.  Here are two articles that fully describe the GC process:
  http://msdn.microsoft.com/en-us/magazine/bb985010.aspx
  http://msdn.microsoft.com/en-us/magazine/bb985011.aspx

Here is reference GC pages:
  http://msdn.microsoft.com/en-us/library/0xy59wtx(VS.80).aspx

I don't think there is any way to STOP garbage collection, but there are ways you can force a collection to limit its effects on critical sections:
  http://www.dotnetuncle.com/Framework/50_gc_activities.aspx
  or using code like this:
        ......
        GC.Collect();
        GC.WaitforPendingFinalizers();
        for (int i=0; i<1000; i++)
        {
                somelist.Add(new someobject());
        }
        ......
0
 
LVL 2

Author Comment

by:ebyrne
ID: 24216615
Hi Mogul,

Thanks for the response. So you state that "when [GC] occurs it will freeze all threads in the application domain". Do you have any reference point for that? That's the primary point I'm after, whether that occurs on the AppDomain or process level, and I didn't find an answer in those articles. I've seen some references (mainly boards) saying it happens on the process level, but haven't found a source I could trust yet (and it's kinda hard to test definitively for..).

Anyone have such a reference?


[As a side note, the last recommendation there is very dangerous. Not only are you forcing a GC, but you've only made a GC less likely by attempting to preempt your allocations. If someone else really needs to go such a road (and you prob shouldn't), you're gonna want to explore your options. For instance, take a look at: http://blogs.msdn.com/bclteam/archive/2005/06/14/429181.aspx or on the various GC Modes, http://blogs.msdn.com/clyon/archive/2007/03/12/new-in-orcas-part-3-gc-latency-modes.aspx. Post if you need more guidance..]
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 24217738
The reference is in the 2nd article in the heading titled:Performance for Multithreaded Applications

So, when the garbage collector wants to start a collection, all threads executing managed code must be suspended. The runtime has a     few different mechanisms that it uses to safely suspend threads so that a collection may be done. The reason there are multiple mechanisms is to keep threads running as long as possible and to reduce overhead as much as possible. I don't want to go into all the details here, but suffice it to say that Microsoft has done a lot of work to reduce the overhead involved with performing a collection. Microsoft will continue to modify these mechanisms over time to help ensure efficient garbage collections.



I agree with your second comment.  You probably should not muck with the GC class until you have exhausted all other code optimization tricks:
  -Using classes that optimize large allocations (i.e. StringBuilder instead of string+string)
  -Clearing out references to objects not being used anymore
  -Creating objects that implement the IDisposible interface when necessary
  -Using the "Using" clause for IDisposable objects
0
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 
LVL 2

Author Comment

by:ebyrne
ID: 24218095
Hi Mogal,

I'm probably dense here, but I still don't see the answer. I agree with the first statement that all threads are suspend. Where does it indicate whether that refers to all threads in the current process or all threads in the current AppDomain?

Thanks again.
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 24219322
I found another thread that had some sample code.

http://stackoverflow.com/questions/241537/what-is-the-scope-of-finalizer-thread-per-application-domain-or-per-process

I modified the code to make it more random and took out the GC.WaitForPendingFinalizers()
and got this Result:
using System;
 
class Test
{
    static void Main()
    {
        AppDomain.CreateDomain("First")
                 .ExecuteAssembly("ShowFinalizerThread.exe");
        AppDomain.CreateDomain("Second")
                 .ExecuteAssembly("ShowFinalizerThread.exe");
    }
}
 
//In another project
using System;
using System.Threading;
 
class ShowFinalizerThread
{
    static Random rng = new Random();
    string RandomString;
    ShowFinalizerThread()
    {
        RandomString = BuildRandomString();
    }
    ~ShowFinalizerThread()
    {
        Console.WriteLine("Thread/domain: {0}/{1}:({2},{3},{4})",
                          Thread.CurrentThread.ManagedThreadId,
                          AppDomain.CurrentDomain.FriendlyName,
                          GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2));
        
        if (rng.Next(10) == 0)
        {
            Console.WriteLine("Hanging!");
            Thread.Sleep(rng.Next(2000));
        }
    }
 
    private string BuildRandomString()
    {
        string RandomString = "This is Random Padded".PadRight(rng.Next(1000), 'X');
        return RandomString;
    }
 
    static void Main()
    {
        new Thread(LoopForever).Start();
    }
 
    static void LoopForever()
    {
        while (true)
        {
            new ShowFinalizerThread();
            if (rng.Next(1000) == 0)
            {
                GC.Collect();
            }
            Thread.Sleep(0);
        };
    }
}

Open in new window

AppDomainTest.png
0
 
LVL 21

Accepted Solution

by:
MogalManic earned 2000 total points
ID: 24219352
The three numbers in parentheses are the Garbage collection counts for each Generation (0, 1, 2).  You can see that each application domain has done the same # of garbage collections (even though I modified the code to do the garbage collections randomly)
0
 
LVL 2

Author Comment

by:ebyrne
ID: 24219640
Process it is.

You know, it's embarrassing, but I didn't even think to look at the collection count, that makes perfect sense of course. That's for taking the time to code it up and test it out Mogal, much appreciated!

Thanks again!
0
 
LVL 2

Author Closing Comment

by:ebyrne
ID: 31573241
Much thanks Mogal, I appreciate all the effort. Beyond and above for sure.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question