Question

Ive checked already some answers, but still Im not convinced what is this right approach of acquiring and releasing COM objects in parallel.

In particular I use a Parallel.ForEach to increase performance, and inside it, it makes calls to MS.Outlook (2010 ExchangeServer). However, by releasing the COM objects I get occasionally COMExceptions.

What is the right approach of working with COM objects with the Parallel library ?

System.Threading.Tasks.Parallel.ForEach(myList, myItem =>
{
     String freeBusySlots = "";
     Outlook.Recipient myReceipient = null;

     try
     {
         myReceipient = namespaceMAPI.CreateRecipient(myItem.ToString());
     }
     catch (Exception ex)
     {
         ...
     }
     finally
     {
        if (myReceipient == null)
        {
            ...
        }

        Marshal.ReleaseComObject(myReceipient ); // -> I get an exception here sometimes ... how to avoid this
        myReceipient = null;
     }
}); // Parllel.forEach

No correct solution

OTHER TIPS

Outlook Object Model cannot be used from secondary threads. Sometimes it works, but it tends to bomb out at the most inappropriate moment.

As of Outlook 2013, Outlook will immediately raise an error if an OOM object is accessed from a secondary thread.

If your code is running from another application, keep in mind that all calls will be serialized to the main Outlook thread anyway so there is really no point using multiple threads.

Also note that Extended MAPI (C++ or Delphi only) or Redemption (which wraps Extended MAPI and can be accessed from any language - I am its author) can be used from multiple threads, but your mileage will vary depending on the particular MAPI provider (IMAP4 store provider is the worst).

As a general rule you should never be using ReleaseComObject. Instead just wait for the RCW object to be collected and let the GC do the work for you. Using this API correctly is extremely hard.

Additionally it's very likely that all of Outlooks COM objects live in the STA. If that is the case there is nothing gained by operating over them in parallel. Every call made from a background thread will simply be marashalled back to the foreground thread for processing. Hence the background thread will add no value, just confusion.

I'm not 100% certain these are STA objects but I'd be very surprised if they weren't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top