I have a main class in Wpf so it's in a MTA and I have to deal with a COM object that needs to be in a STA.
SO I have the following code to create an instance of an object.
COMObject localCOMObject;
Thread thread = new Thread(() =>
{
try { localCOMObject = new COMObject(); }
finally { DidFinish= 1; }
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
And I also have a list object that have a reference to this object(WorkingObjects)
List<WorkingObject> WorkingObjects= new List<WorkingObject>();
WorkingObject.Add(new WorkingObject(localCOMObject));
...
Further in my code I run
await Task.Run(() =>
{
Parallel.ForEach(WorkingObjects, WorkingObject=>
{
WorkingObject.Execute();
});
});
And within my Execute method I use my COMObject object and this is when I get the exception:
COM object that has been separated from its underlying RCW can not be used.
It use to work when My code was:
await Task.Run(() =>
{
COMObject localCOMObject = new COMObject();
Parallel.ForEach(WorkingObjects, WorkingObject=>
{
WorkingObject=localCOMObject ;
WorkingObject.Execute();
});
});
But now I need to do things with this outside of my task.