我对 C# 还是有点陌生,尤其是 C# 中的线程。 我正在尝试启动一个需要单线程单元的函数 (STAThread)
但我无法编译以下代码:
该函数在名为 MyClass
的单独类中如下所示:
internal static string DoX(string n, string p)
{
// does some work here that requires STAThread
}
我已经尝试在函数之上添加 [STAThread] 属性,但它不起作用。
所以我正在尝试创建一个新线程,如下所示:
Thread t = new Thread(new ThreadStart(MyClass.DoX));
但这不会编译(最好的重载方法有无效参数错误)。但是在线示例非常相似(example here) 我做错了什么,我怎样才能让函数在新的 STA 线程中运行?
谢谢
最佳答案
Thread thread = new Thread(() => MyClass.DoX("abc", "def"));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
如果您需要该值,您可以将其“捕获”回一个变量,但请注意,该变量在另一个线程结束之前不会有该值:
int retVal = 0;
Thread thread = new Thread(() => {
retVal = MyClass.DoX("abc", "def");
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
或者更简单:
Thread thread = new Thread(() => {
int retVal = MyClass.DoX("abc", "def");
// do something with retVal
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
关于c# - 在 C# 中启动 STAThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11681666/