在 C# 中启动 STAThread
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11681666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Starting an STAThread in C#
提问by Saher Ahwal
I am still kind of new to C#, and especially threading in C#. I am trying to start a function that requires a single threaded apartment (STAThread)
我对 C# 还是有点陌生,尤其是 C# 中的线程。我正在尝试启动一个需要单线程单元(STAThread)的函数
But I am not able to compile the following code:
但我无法编译以下代码:
The function looks as follows in a separate class called MyClass:
该函数在名为 的单独类中如下所示MyClass:
internal static string DoX(string n, string p)
{
// does some work here that requires STAThread
}
I have tried the attribute [STAThread] on top of the function but that does not work.
我已经尝试了函数顶部的属性 [STAThread] 但这不起作用。
So I am trying to create a new Thread as follows:
所以我试图创建一个新的线程如下:
Thread t = new Thread(new ThreadStart(MyClass.DoX));
but this will not compile (The best overloaded method has invalid arguments error). However the example online is very similar (example here)What am I doing wrong and how can I simply make a function run in a new STA thread?
但这不会编译(最好的重载方法有无效参数错误)。但是,在线示例非常相似(此处的示例)我做错了什么,如何简单地在新的 STA 线程中运行函数?
Thanks
谢谢
采纳答案by Marc Gravell
Thread thread = new Thread(() => MyClass.DoX("abc", "def"));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
If you need the value, you can "capture" that back into a variable, but note that the variable won't have the value until the end of the other thread:
如果您需要该值,您可以将其“捕获”回变量中,但请注意,该变量直到另一个线程结束时才具有该值:
int retVal = 0;
Thread thread = new Thread(() => {
retVal = MyClass.DoX("abc", "def");
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
or perhaps simpler:
或者更简单:
Thread thread = new Thread(() => {
int retVal = MyClass.DoX("abc", "def");
// do something with retVal
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

