在.NET中,当我在一个额外的线程中运行表单时,如何设置STAThread? [英] in .NET, How do I set STAThread when I'm running a form in an additional thread?

查看:217
本文介绍了在.NET中,当我在一个额外的线程中运行表单时,如何设置STAThread?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在第二个线程中运行表单。如果我在Ctrl-C上复制剪贴板上的文本,我得到一个异常,当前线程必须设置为单线程公寓(STA)在OLE调用之前(使用剪贴板涉及OLE显然)。

将[STAThread]与我的线程proc,这是我的第二个线程的入口点工作。 >

  [STAThread] 
private void MyFormThreadproc(object o)
{
form = new MyForm ;
Application.Run(form);
}


解决方案

创建线程时,调用 SetApartmentState() 方法,你不能这样做的线程池线程。



例如:

 线程线程= new Thread(threadAction); 
thread.SetApartmentState(ApartmentState.STA );
thread.Start();


I'm running a form in a second thread. If I do Ctrl-C to copy text on the clipboard, I get an Exception, "Current thread must be set to a single thread apartment (STA) before OLE calls can be made. (Using the clipboard involves OLE apparently).

Putting the [STAThread] with my thread proc, which is the entry point of my second thread does NOT work. What will work?

[STAThread]
private void MyFormThreadproc(object o)
{
    form = new MyForm();
    Application.Run(form);
}

解决方案

When you create the thread, call the SetApartmentState() method before you start it. You can't do this for threadpool threads.

For example:

Thread thread = new Thread(threadAction);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

这篇关于在.NET中,当我在一个额外的线程中运行表单时,如何设置STAThread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆