ezG
ezG

Reputation: 421

Outlook: Releasing COM objects retrieved using delegates

Just for the sake of argument, let's say you are using the Attachments collection. This collection implements IEnumerable.

What is going on behind the scenes if we were to do something like this? Does each iteration of through the collection create an "AttachmentS" object that cannot be released?

  void SomeEventHandler( Attachments attachments, object args )
  {
      Outlook._Attachment attachment = attachments.First( x => x.Subject == "I like COM" );

     // do stuff
     Marshal.ReleaseComObject(attachment);
  }

The call to First will iterate through the collection of COM objects. Will it act like foreach and cause COM references we cannot release?

Upvotes: 0

Views: 48

Answers (1)

Eugene Astafiev
Eugene Astafiev

Reputation: 49395

Will it act like foreach and cause COM references we cannot release?

Yes, it will. Use the for loop with releasing statements in the code instead. It is not recommended to use LINQ, lambda expressions and etc. with Office RCW objects. Following that, you will not be able to release COM objects in a timely manner.

To understand how the First method works under the hood I'd suggest looking at the CIL (or MSIL) code generated by the .net framework compilers.

Upvotes: 1

Related Questions