开始在C#中STAThread [英] Starting an STAThread in C#
问题描述
我仍然到C#的一种新的,特别是在C#中的线程。 我试图启动一个函数,需要一个单线程单元( STAThread )
但我不能够编译如下code:
该功能看起来在一个单独的类名为如下: MyClass的
:
内部静态字符串DOX(串N,串P)
{
//做了一些工作,在这里,需要STAThread
}
我已经试过属性[STAThread]功能的顶部,但不起作用。
所以,我想创建一个新的主题如下:
线程t =新主题(新的ThreadStart(MyClass.DoX));
但这不会编译(最好重载的方法有无效的参数错误)。不过网上的例子非常相似(例如这里) 我在做什么错了,我怎么能简单地做出一个新的STA线程函数运行?
感谢
线程的线程=新主题(()=> MyClass.DoX(ABC,高清)) ;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
如果你需要的价值,你可以捕获的备份到一个变量,但请注意,该变量不会有值,直到另一个线程结束:
INT retVal的= 0;
线程线程=新主题(()=> {
retVal的= MyClass.DoX(ABC,DEF);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
或者是简单的:
线程的线程=新主题(()=> {
INT retVal的= MyClass.DoX(ABC,高清);
//做些什么retVal的
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
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)
But I am not able to compile the following code:
The function looks as follows in a separate class called 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.
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?
Thanks
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();
这篇关于开始在C#中STAThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!