ApartmentState Enumerazione

Definizione

Specifica lo stato dell'apartment di un Thread.Specifies the apartment state of a Thread.

public enum class ApartmentState
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public enum ApartmentState
type ApartmentState = 
Public Enum ApartmentState
Ereditarietà
ApartmentState
Attributi

Campi

MTA 1

Thread creerà ed immetterà un apartment con multithreading.The Thread will create and enter a multithreaded apartment.

STA 0

Thread creerà ed immetterà un apartment a thread singolo.The Thread will create and enter a single-threaded apartment.

Unknown 2

La proprietà ApartmentState non è stata impostata.The ApartmentState property has not been set.

Esempi

Nell'esempio di codice riportato di seguito viene illustrato come impostare lo stato dell'Apartment di un thread.The following code example demonstrates how to set the apartment state of a thread.

using namespace System;
using namespace System::Threading;
ref class ApartmentTest
{
public:
   static void ThreadMethod()
   {
      Thread::Sleep( 1000 );
   }

};

int main()
{
   Thread^ newThread = gcnew Thread( gcnew ThreadStart( &ApartmentTest::ThreadMethod ) );
   newThread->SetApartmentState(ApartmentState::MTA);
   
   Console::WriteLine( "ThreadState: {0}, ApartmentState: {1}", newThread->ThreadState.ToString(), newThread->GetApartmentState().ToString() );
   newThread->Start();
   
   // Wait for newThread to start and go to sleep.
   Thread::Sleep( 300 );
   try
   {
      
      // This causes an exception since newThread is sleeping.
      newThread->SetApartmentState(ApartmentState::STA);
   }
   catch ( ThreadStateException^ stateException ) 
   {
      Console::WriteLine( "\n{0} caught:\n"
      "Thread is not in the Unstarted or Running state.", stateException->GetType()->Name );
      Console::WriteLine( "ThreadState: {0}, ApartmentState: {1}", newThread->ThreadState.ToString(), newThread->GetApartmentState().ToString() );
   }

}

using System;
using System.Threading;

class ApartmentTest
{
    static void Main()
    {
        Thread newThread = 
            new Thread(new ThreadStart(ThreadMethod));
        newThread.SetApartmentState(ApartmentState.MTA);

        Console.WriteLine("ThreadState: {0}, ApartmentState: {1}", 
            newThread.ThreadState, newThread.ApartmentState);

        newThread.Start();

        // Wait for newThread to start and go to sleep.
        Thread.Sleep(300);
        try
        {
            // This causes an exception since newThread is sleeping.
            newThread.SetApartmentState(ApartmentState.STA);
        }
        catch(ThreadStateException stateException)
        {
            Console.WriteLine("\n{0} caught:\n" +
                "Thread is not in the Unstarted or Running state.", 
                stateException.GetType().Name);
            Console.WriteLine("ThreadState: {0}, ApartmentState: {1}",
                newThread.ThreadState, newThread.GetApartmentState());
        }
    }

    static void ThreadMethod()
    {
        Thread.Sleep(1000);
    }
}
Imports System.Threading

Public Class ApartmentTest

    <MTAThread> _
    Shared Sub Main()
    
        Dim newThread As Thread = New Thread(AddressOf ThreadMethod)
        newThread.SetApartmentState(ApartmentState.MTA)

        Console.WriteLine("ThreadState: {0}, ApartmentState: {1}", _
            newThread.ThreadState, newThread.GetApartmentState())

        newThread.Start()

        ' Wait for newThread to start and go to sleep.
        Thread.Sleep(300)
        Try
            ' This causes an exception since newThread is sleeping.
            newThread.SetApartmentState(ApartmentState.STA)
        Catch stateException As ThreadStateException
            Console.WriteLine(vbCrLf & "{0} caught:" & vbCrLf & _
                "Thread is not In the Unstarted or Running state.", _
                stateException.GetType().Name)
            Console.WriteLine("ThreadState: {0}, ApartmentState: " & _
                "{1}", newThread.ThreadState, newThread.GetApartmentState())
        End Try

    End Sub

    Shared Sub ThreadMethod()
        Thread.Sleep(1000)
    End Sub

End Class

Commenti

Un Apartment è un contenitore logico all'interno di un processo per gli oggetti che condividono gli stessi requisiti di accesso ai thread.An apartment is a logical container within a process for objects sharing the same thread access requirements. Tutti gli oggetti nello stesso Apartment possono ricevere chiamate da qualsiasi thread dell'Apartment.All objects in the same apartment can receive calls from any thread in the apartment. Il .NET Framework non utilizza gli Apartment e gli oggetti gestiti sono responsabili dell'utilizzo di tutte le risorse condivise in modo thread-safe.The .NET Framework does not use apartments, and managed objects are responsible for using all shared resources in a thread-safe manner themselves.

Poiché le classi COM utilizzano Apartment, il Common Language Runtime necessario creare e inizializzare un Apartment quando si chiama un oggetto COM in una situazione di interoperabilità COM.Because COM classes use apartments, the common language runtime needs to create and initialize an apartment when calling a COM object in a COM interop situation. Un thread gestito può creare e immettere un Apartment a thread singolo (STA) che consente solo un thread o un Apartment a thread multipli (MTA) che contiene uno o più thread.A managed thread can create and enter a single-threaded apartment (STA) that allows only one thread, or a multithreaded apartment (MTA) that contains one or more threads. È possibile controllare il tipo di Apartment creato impostando la ApartmentState proprietà del thread su uno dei valori ApartmentState dell'enumerazione.You can control the type of apartment created by setting the ApartmentState property of the thread to one of the values of the ApartmentState enumeration. Poiché un determinato thread può solo inizializzare un apartment COM una sola volta, non è possibile modificare il tipo di Apartment dopo la prima chiamata al codice non gestito.Because a given thread can only initialize a COM apartment once, you cannot change the apartment type after the first call to the unmanaged code.

Per ulteriori informazioni, vedere Thread, Threading gestito e non gestitoe interoperabilità com avanzata.For more information, see Thread, Managed and Unmanaged Threading, and Advanced COM Interoperability.

Si applica a

Vedi anche