【发布时间】:2011-03-11 03:49:18
【问题描述】:
我收到以下错误:
"COM object that has been separated from its underlying RCW cannot be used."
我确定问题是因为 COM 对象不是在它创建的线程上调用的 - STA。我尝试实现 IDisposable,但它对我不起作用。
有几个帖子处理类似的问题,但仍然没有解决我的问题:
Is it safe to call an RCW from a finalizer? Release Excel Object In My Destructor
谁能发布一个示例/解释如何从另一个线程正确访问 COM 对象?
这是显示问题的最少代码:
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();
// this method call works
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();
// this method call fails
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;
}
}
}
【问题讨论】:
标签: c# wpf multithreading com interop