The difference between STA and MTA threading patterns

Source: Internet
Author: User

Article Source: http://blog.csdn.net/fragno/article/details/7982044

Sta:single-thread Apartment, Chinese called single-threaded suite. is to create a memory structure when the COM library is initialized, and then associate it with the line threads that calls CoInitialize. This memory structure will have one for each thread. A COM object that supports STA can only be used in the line thread that created it, and other threads will fail if it is created again.

Mta:mutil-thread Apartment, Chinese called multi-threaded suite. The COM library creates a memory structure in the process that can only have one in the entire process and then associates it with the line threads that calls CoInitializeEx. COM objects that support the MTA can be used in any line thread. Many calls to it will be encapsulated as messages.

In fact, the STA and MTA are COM's set of threading models that are used to ensure the synchronization of your component code in multithreaded situations. For example, there is a COM object inside it has a static variable Ghello, then this object regardless of how many instances generated for Ghello in memory can only have one copy, then if there are two different instances in two threads at the same time to read and write it, there is a possibility of error, so it is necessary to have a mechanism for synchronous protection, The STA or MTA is the mechanism.

Process relative to a small town, the thread is equivalent to the inhabitants of this town, the STA (single-threaded suite) is the equivalent of a residential room, is private, the MTA (multi-threaded suite) is equivalent to a hotel, is common, COM objects are equivalent to a residential room or hotel items. Then it's good to understand, a small town (process) Can have a lot of (resident) threads, the town (process) has only one hotel (MTA), but there can be a lot of residential rooms (STA). Only residents (threads) enter the room (residential or hotel, STA or MTA) to use the room items (COM objects), residents ( STA) (COM object) can only be used by the owner of the house (the thread that created the STA), and other residents (threads) cannot access it. Similarly, only residents (threads, which can have more than one) residing in the hotel (MTA) can access items (COM objects) in the hotel (MTA). However, because it is common, it is necessary to allocate (synchronize) properly to create no confusion.


. NET supports two types of threading models: STA and MTA.
STA (single threaded apartments). Apartment is just a logical concept that can contain one or more threads. An AppDomain can include one or more apartment. STA means that the apartment can contain only one thread.
MTA (Multi threaded apartments). means that the apartment can contain multiple thread.
The biggest difference between STA and MTA is that the MTA can execute multiple threads concurrently with all shared resources in the same apartment. While multiple STA can share data, but cannot execute threads concurrently, there are performance issues.

Creation of Threads:
When a new STA thread is created, the CLR creates a apartment and thread (subordinate to the apartment) in the AppDomain. If you are creating an MTA thread, the CLR checks to see if the AppDomain has a apartment that holds the MTA and creates an MTA and thread (subordinate to the apartment) if there is only one that creates the thread into the MTA.
We can set the properties of the thread. For example t.apartmentstate = ApartmentState.STA;

The use of threads differs:
We should only use the STA threading mode when accessing sta-based COM components. You can view the COM thread pattern under the registry's Hkey_classes_root\clsid\{class ID of the COM component} \InProcServer32. If the value is apartment, then the COM can only run in STA mode. The other values are free (MTA), Both (STA+MTA), single (can only be executed in one thread).
In other cases, we should use the MTA thread, although we need to worry about the synchronization of resources between threads.


Example:
I now want to implement a scenario that copies pictures from a Word document and saves them in a program in Windows Form.
Open the Word document, copy the picture information to the pasteboard, and then get the picture information from the pasteboard and save it to your local directory.

Description: (originally placed under the code, but after the post is blocked by the code does not show)
If the method is called directly in the event of a button, the interface becomes unresponsive. So we need to consider using multithreading to solve this problem. Thread t = new Thread (new Theardstart (copyimages); T.start ();
If this is the case, the program will have an error: Either show an exception or no exception, but Clipboard is empty and cannot get any data! Why is it?
Because Word.Application is automation and sta-based, it cannot be called in a thread that does not have a specified threadapartment. So it caused a variety of errors, so it needs to be in T. Start (), preceded by T. Apartment = ApartmentState.STA; so it's perfectly normal.
For the multi-threaded MTA We see a lot more, no longer an example.

Another point does not understand, I monitor the task manager found that I am executing thread t = new Thread (new Theardstart (copyimages); t.apartment = ApartmentState.STA; T.start (); The number of threads in the program is then increased from 3 to 6, if the thread that created the MTA is incremented by only 1. My understanding is that the STA thread is added to the need to maintain the internal hidden window classes and message queues.

Here's how it's implemented:
1private void Copyimages ()
2 {
3 Word.Application app = null;
4 Word.Document doc = null;
5
6 app = new ApplicationClass ();
7
8 Try
9 {
Ten Object fileName = @ "E:\A.doc";
doc = App. Documents.Open (ref filename,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref Missing,ref Missing,
Ref missing,ref Missing,ref missing,ref missing,ref missing,ref missing);
13
int count = doc. Inlineshapes.count;
for (int i=1;i<=count;i++)
16 {
Doc. Inlineshapes[i]. Range.Copy ();
18
if (clipboard.getdataobject () = null)
20 {
IDataObject data = Clipboard.getdataobject ();
22
if (data. GetDataPresent (Dataformats.bitmap))
24 {
Image image = (image) data. GetData (dataformats.bitmap,true);
Image. Save ("e:\\" + i.tostring () + ". jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
27}
-Else
29 {
Lst_Items.Items.Add (Doc. Name + "; no correct picture data");
31}
32}
+ Else
34 {
Lst_Items.Items.Add (Doc. Name + "; Clipboard is empty");
36}
37}
38
39}
(Exception ex)
41 {
Lst_Items.Items.Add (Doc. Name + "error occurred;" + ex. Message);
43}
Finally
45 {
if (doc! = null)
Doc. Close (ref missing,ref missing,ref missing);
if (app! = null)
App. Quit (ref missing,ref missing,ref missing);
50}

The difference between STA and MTA threading patterns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.