That explains why it did work for me with Managed C++ because I never
initialized COM STA.
Thanks!!

-----Original Message-----
From: Greg Reinacker [mailto:[EMAIL PROTECTED]]
Sent: Monday, May 20, 2002 4:54 PM
To: [EMAIL PROTECTED]
Subject: Re: [DOTNET] strange behaviour with Garbage Collector


This has to do with the COM apartment that your thread enters.  If it
enters an STA, then the COM object cannot be completely released until
the apartment's thread spins its message loop.  In the example, that
will not happen until the next time an out-of-apartment object is
created.  If, instead, the thread enters the MTA, then the object will
be immediately released at GC.Collect() time, as expected.

Here's the example code I used:

using System;

class Class1
{
   // If you uncomment the following line, you will reproduce the
   // behavior we have been discussing
   // [STAThread]
   static void Main(string[] args)
   {
      Excel.ApplicationClass appClass = new Excel.ApplicationClass();
      appClass = null;
      GC.Collect();

      Console.WriteLine("reference null");
      Console.WriteLine("press return to continue");
      Console.ReadLine();

      appClass = new Excel.ApplicationClass();
      appClass = null;
      GC.Collect();

      Console.WriteLine("reference null");
      Console.WriteLine("press return to continue");
      Console.ReadLine();
   }
}

Incidentally, Chris's suggestion of calling GC.WaitForPendingFinalizers
will also work; that seems to indicate that that function will spin a
message loop while waiting if the thread has entered a STA.  Probably a
good idea, to avoid potential deadlock in finalizers...

On another unrelated note, this list is soooooo annoying when you post
something and it never shows up.  Grr...

Greg Reinacker
Reinacker & Associates, Inc.
http://www.rassoc.com


On Mon, 20 May 2002 11:16:08 -0600, Brad Wilson <[EMAIL PROTECTED]>
wrote:

>Howard Bartfield wrote:
>
>> i'm not convinced it's to do with 2 GCs, because the following
>> doesn't work either:
>
>> Excel.ApplicationClass appClass =  new Excel.ApplicationClass();
>> appClass = null; GC.Collect();
>> GC.Collect();
>
>Well, then, my last estimation would be to say that the objects just
aren't
>finalizaed. Which means either (1) the system keeps some sort of a list

>of outstanding COM objects, and weak references to the owning object
>(would seem rather silly), or (2) you have to release COM servers
>manually,
period.
>
>Since I don't have access to a .NET SDK here, I can't really test
>what's right.
>
>Adam Nathan's book might shed some light, too.
>
>Brad
>
>--
>Read my web log at http://www.quality.nu/dotnetguy/

You can read messages from the DOTNET archive, unsubscribe from DOTNET,
or subscribe to other DevelopMentor lists at http://discuss.develop.com.

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to