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

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

问题描述

我运行在第二个线程的形式。如果我按Ctrl-C对剪贴板复制文本,我得到一个例外,当前线程必须设置为单个线程单元(STA)可制成OLE调用之前。(使用剪贴板涉及OLE显然)。

把[STAThread]我的线程PROC,这是我的第二个线程的入口点确实的的工作。什么工作?

  [STAThread]
私人无效MyFormThreadproc(对象o)
{
    形式=新建MyForm();
    Application.Run(形式);
}


解决方案

在创建线程,调用<一个href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.setapartmentstate.aspx\"><$c$c>SetApartmentState()方法你开始之前。不能为线程池线程做到这一点。

例如:

 线程线程=新主题(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天全站免登陆