Set ApartmentState for ArcObjects-logic in separate threads

Problem context We use a backgroundworker to load MXD documents from several places of the system and extract meta data and thumbnails which a GUI component...

Problem context

We use a backgroundworker to load MXD documents from several places of the system and extract meta data and thumbnails which a GUI component shows in an asynchron way.

The unit tests for this logic throws an exception during the access the thumbnail:

'mapDocument.Thumbnail' threw an exception of type 'System.Runtime.InteropServices.COMException'

exception = {"Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))"
TargetSite = {stdole.IPicture get_Thumbnail()}

Solution

Although the unit test method was marked with [STAThread] a new spawned thread does not get this information from the creating thread. The apartment state must explicit set for the new thread:

var thread = new Thread(ReadMapDocuments);
thread.SetApartmentState(ApartmentState.STA);
thread.Start(configItems);