简体   繁体   中英

Can more than one thread have STA apartment set?

I'm thinking of using this code to detect if the thread is the main (UI) thread.

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

It certainly appears to work fine with worker threads running tasks returning false, just wondering if it is generally true.

If it's relevant, this is a WPF application.

This is similar to my other question: How do I assert that the code is running in the main thread? But no one suggested this solution.

Yes, you can set STA on other threads when you create them. Thread pool threads are in the MTA.

Yes you can have multiple threads have STA apartment. But you MUST NOT swap framework elements between threads, that will still cause errors. Meaning you can't make a textbox control and populate it in a worker thread that is also STA and then pass it to you main thread (which is also STA) and add it to a form. That will still cause errors. So the question is, why do you want to set multiple threads to STA?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM