0

我正在考虑使用此代码来检测线程是否是主(UI)线程。

public static bool IsMainThread()
{
    return Thread.CurrentThread.GetApartmentState() == ApartmentState.STA;
}

运行返回 false 的任务的工作线程似乎可以正常工作,只是想知道它是否普遍正确。

如果相关,这是一个 WPF 应用程序。

这类似于我的另一个问题:如何断言代码正在主线程中运行?但是没有人建议这种解决方案。

4

3 回答 3

1

According to the documentation for STAThreadAttribute, you can not have more than one thread that is STA (you can't even truely have one unless you are using COM interop).

"Apply this attribute to the entry point method (the Main() method in C# and Visual Basic). It has no effect on other methods."

Since .Net 2.0 the Single Threaded Apartment is only intended for use when performing COM interop.

"COM threading models only pertain to applications that use COM interop. Using this attribute in an application that does not use COM interop has no effect."

"In the .NET Framework version 2.0, new threads are initialized as ApartmentState.MTA if their apartment state has not been set before they are started. The main application thread is initialized to ApartmentState.MTA by default."

Reference: http://msdn.microsoft.com/en-us/library/system.stathreadattribute(v=vs.100).aspx

于 2012-12-03T20:30:18.997 回答
1

是的,您可以在创建其他线程时在其他线程上设置 STA。线程池线程在 MTA 中。

于 2012-12-03T16:06:37.560 回答
1

是的,您可以让多个线程拥有 STA 单元。但是你不能在线程之间交换框架元素,这仍然会导致错误。这意味着您不能制作文本框控件并将其填充到也是 STA 的工作线程中,然后将其传递给您的主线程(也是 STA)并将其添加到表单中。这仍然会导致错误。那么问题来了,为什么要给STA设置多个线程呢?

于 2012-12-03T16:07:09.987 回答