在 C# 中启动 STAThread

编程入门 行业动态 更新时间:2024-10-09 16:27:28
本文介绍了在 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

本文发布于:2023-11-27 12:44:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638127.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:STAThread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!