bav*_*aza 14 c# com interop message-queue sta
因此,在此之后,我决定在专用的STA线程上显式实例化COM对象.实验表明COM对象需要一个消息泵,我通过调用它来创建Application.Run():
private MyComObj _myComObj;
// Called from Main():
Thread myStaThread = new Thread(() =>
{
_myComObj = new MyComObj();
_myComObj.SomethingHappenedEvent += OnSomthingHappened;
Application.Run();
});
myStaThread.SetApartmentState(ApartmentState.STA);
myStaThread.Start();
Run Code Online (Sandbox Code Playgroud)
如何从其他线程发布STA线程的消息泵消息?
注意: 为了简洁起见,我对问题进行了大量编辑.@Servy的答案的某些部分现在似乎无关紧要,但它们是针对原始问题的.
Han*_*ant 20
请记住,Windows为STA线程创建的消息队列已经是线程安全队列的实现.所以只需将它用于您自己的目的.这是一个可以使用的基类,派生自己的基类来包含COM对象.重写Initialize()方法,一旦线程准备开始执行代码,就会调用它.不要忘记在覆盖中调用base.Initialize().
您希望在该线程上运行代码,然后使用BeginInvoke或Invoke方法,就像您对Control.Begin/Invoke或Dispatcher.Begin/Invoke方法一样.调用它的Dispose()方法来关闭线程,它是可选的.请注意,当您100%确定所有COM对象都已完成时,这样做是安全的.由于您通常没有这种保证,所以最好不要这样做.
using System;
using System.Threading;
using System.Windows.Forms;
class STAThread : IDisposable {
public STAThread() {
using (mre = new ManualResetEvent(false)) {
thread = new Thread(() => {
Application.Idle += Initialize;
Application.Run();
});
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
mre.WaitOne();
}
}
public void BeginInvoke(Delegate dlg, params Object[] args) {
if (ctx == null) throw new ObjectDisposedException("STAThread");
ctx.Post((_) => dlg.DynamicInvoke(args), null);
}
public object Invoke(Delegate dlg, params Object[] args) {
if (ctx == null) throw new ObjectDisposedException("STAThread");
object result = null;
ctx.Send((_) => result = dlg.DynamicInvoke(args), null);
return result;
}
protected virtual void Initialize(object sender, EventArgs e) {
ctx = SynchronizationContext.Current;
mre.Set();
Application.Idle -= Initialize;
}
public void Dispose() {
if (ctx != null) {
ctx.Send((_) => Application.ExitThread(), null);
ctx = null;
}
}
private Thread thread;
private SynchronizationContext ctx;
private ManualResetEvent mre;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8494 次 |
| 最近记录: |