我仍然是C#的新手,尤其是C#中的线程.我正在尝试启动一个需要单线程单元的函数(STAThread)
但我无法编译以下代码:
该函数在一个名为的单独类中如下所示MyClass
:
internal static string DoX(string n, string p)
{
// does some work here that requires STAThread
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了函数顶部的[STAThread]属性,但这不起作用.
所以我试图创建一个新的Thread如下:
Thread t = new Thread(new ThreadStart(MyClass.DoX));
Run Code Online (Sandbox Code Playgroud)
但这不会编译(最好的重载方法有无效的参数错误).然而,在线示例非常相似(这里的示例) 我做错了什么,我怎样才能简单地在新的STA线程中运行函数?
谢谢
Mar*_*ell 39
Thread thread = new Thread(() => MyClass.DoX("abc", "def"));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Run Code Online (Sandbox Code Playgroud)
如果您需要该值,则可以将其"捕获"回变量,但请注意,该变量在其他线程结束之前不会具有该值:
int retVal = 0;
Thread thread = new Thread(() => {
retVal = MyClass.DoX("abc", "def");
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Run Code Online (Sandbox Code Playgroud)
或者更简单:
Thread thread = new Thread(() => {
int retVal = MyClass.DoX("abc", "def");
// do something with retVal
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27825 次 |
最近记录: |