'Asnchronous\background method execution C#, Outlook VSTO plugin

I have searched and have not yet found a good solution. I am writing a simple add-in for Outlook that would download\cache certain messages based on certain criteria.

It works reliably, except for performance. I have a method\function that runs at startup. But the Application hangs until it is done executing.

How do I run my code asynchronously, and just run in the background?

This worked, but was hogging a lot of resources\locking up all the time. Is there a better way? How Start Methods With Arguments Using Thread



Solution 1:[1]

You should never use OOM on secondary threads. Most Office applications use the single-threaded apartment model which doesn't support multithreading. Read more about that in the Outlook Crashes When Using Outlook Object Model in Multiple Threads article.

As a possible workaround you may consider using a low-level API on which Outlook is built - Extended MAPI or just any wrapper around that API such as Redemption.

Solution 2:[2]

A Eugene mentioned, OOM cannot be used on secondary threads when running inside the outlook.exe address space. Starting with Outlook 2016, OOM will raise an exception immediately as soon as it detects access on a secondary thread.

Your options are:

  1. Don't do anything OOM related on the secondary thread. Retrieve the data on the primary thread, runs the secondary thread without touching any OOM objects, update (if necessary) OOM objects on the primary thread.

  2. Extended MAPI (C++ or Delphi only)

  3. Redemption (I am its author) - save the value of the Namespace.MAPIOBJECT property (it returns IMAPISession Extended MAPI interface) in a variable. On the secondary thread, create an instance of the RDOSession object, sets the RDOSession.MAPIOBJECT property to the variable set on the main thread - that will share the MAPI session between the threads.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eugene Astafiev
Solution 2