在C#中启动STAThread
我仍然是C#的新手,尤其是C#中的线程。 我正在尝试启动一个需要单线程单元的函数( STAThread )
但我无法编译以下代码:
该函数在名为MyClass
的单独类中如下所示:
internal static string DoX(string n, string p) { // does some work here that requires STAThread }
我已经尝试了函数顶部的[STAThread]属性,但这不起作用。
所以我试图创建一个新的Thread如下:
Thread t = new Thread(new ThreadStart(MyClass.DoX));
但这不会编译(最好的重载方法有无效的参数错误)。 然而,在线示例非常相似(这里的示例)我做错了什么,我怎么能简单地在新的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();