I get the following error:
"COM object that has been separated from its underlying RCW cannot be used."
I am sure that the problem is that the COM object is not called in the thread that was created - STA. I tried to implement IDisposable, but it did not work for me.
There are several posts devoted to a similar problem, but which still do not solve my problem:
Is it safe to call RCW from the finalizer?
Release the Excel object in my destructor
Can someone post an example / explain how a COM object should be correctly accessible from another thread?
Here is the minimal code that shows the problem:
using System;
using System.Threading;
namespace Test.ComInterop
{
public class Program
{
MyCom _myCom;
[STAThread]
static void Main( string[] args )
{
new Program();
}
public Program()
{
_myCom = new MyCom();
string version = _myCom.ComMethod();
StartThread();
}
private void StartThread()
{
Thread t = new Thread( UIRun );
t.SetApartmentState( ApartmentState.STA );
t.Start();
}
void UIRun()
{
TestUI window = new TestUI();
window.Show();
window.Title = _myCom.ComMethod();
window.Closed += ( sender2, e2 )
=> window.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
}
}
class MyCom
{
private dynamic _com;
public MyCom()
{
_com = Activator.CreateInstance(
Type.GetTypeFromProgID( "Excel.Application" ) );
}
public string ComMethod()
{
return (string) _com.Version;
}
}
}