在 C# 中启动 STAThread [英] Starting an STAThread in C#

查看:19
本文介绍了在 C# 中启动 STAThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C# 还是有点陌生​​,尤其是 C# 中的线程.我正在尝试启动一个需要单线程单元的函数(STAThread)

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:

该函数在名为 MyClass 的单独类中如下所示:

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
        }

我已经在函数顶部尝试了属性 [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));

但这不会编译(最好的重载方法有无效参数错误).但是,在线示例非常相似(此处示例)我做错了什么,如何简单地让函数在新的 STA 线程中运行?

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?

谢谢

推荐答案

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();

或者更简单:

Thread thread = new Thread(() => {
    int retVal = MyClass.DoX("abc", "def");
    // do something with retVal
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

这篇关于在 C# 中启动 STAThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆