c# - 在 C# 中启动 STAThread

标签 c# .net wcf sta

我对 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/

相关文章:

c# - string.Join 抛出 OutOfMemory 异常

c# - 服务器和客户端之间的双向通信

c# - 等效于 InsertonSubmit 的 Entity Framework

visual-studio-2008 - 验证(): Attribute 'Factory' is not a valid attribute of element 'ServiceHost'

c# - 检测Canvas上的两个控件是否发生碰撞

c# - Visual Studio 2017 错误 : Cannot find project info for “” This can indicate a missing project reference - with Console App . NET Core 2.1

c# - 异步Client Socket,乱序接收缓冲区数据

c# - 我如何在C#和文本编辑器中获得相同的Regex结果?

c# - 从不同项目的 appsettings.json 中读取多个连接字符串

c# - 如何对具有相同属性名称的多个属性使用 select 方法