In a VSTO addin I am starting a new background STA thread ("Thread B") that creates some COM objects, e.g. a PowerPoint.Shape. Now I would like to be able to access this PowerPoint.Shape in my main VSTO STA thread ("Thread A") but I get a "COM object that has been separated from its underlying RCW cannot be used" exception.
I searched online and found (see comment by Kevin Smyth here: COM object that has been separated from its underlying RCW cannot be used) that this can occur because Thread B is no longer alive when I try to access the object in Thread A.
I know that ideally I should not use a background thread at all here but I still would like to know if it is even possible to pass the COM object created on Thread B to Thread A and access it there even though thread B is no longer running.
'We are on the main thread (Thread A)
Dim output As List(Of PowerPoint.Shape) = DoWorkOnThreadB(oSlide)
'Now when I e.g. try to look at some properties of a shape in the list I get the RCW exception.
Private Shared Function DoWorkOnThreadB(oSlide as PowerPoint.Slide) as List(Of PowerPoint.Shape)
Dim listOfShapes = New List(Of PowerPoint.Shape)()
For each oShape as PowerPoint.Shape in oSlide.Shapes
listOfShapes.Add(oShape)
Next
Return listOfShapes
End Function
I also tried to use a ManualResetEvent to wait in Thread B to keep it alive until I am finished with using the object in Thread A but this did not work.