Thread.ApartmentState Propiedad
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Precaución
The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.
Precaución
The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.
Obtiene o establece el estado de apartamento de este subproceso.
public:
property System::Threading::ApartmentState ApartmentState { System::Threading::ApartmentState get(); void set(System::Threading::ApartmentState value); };
[System.Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)]
public System.Threading.ApartmentState ApartmentState { get; set; }
[System.Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.")]
public System.Threading.ApartmentState ApartmentState { get; set; }
public System.Threading.ApartmentState ApartmentState { get; set; }
[<System.Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)>]
member this.ApartmentState : System.Threading.ApartmentState with get, set
[<System.Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.")>]
member this.ApartmentState : System.Threading.ApartmentState with get, set
member this.ApartmentState : System.Threading.ApartmentState with get, set
Public Property ApartmentState As ApartmentState
Valor de propiedad
Uno de los valores de ApartmentState. El valor inicial es Unknown
.
- Atributos
Excepciones
Se realiza un intento de establecer esta propiedad en un estado que no es un estado de contenedor válido (un estado distinto de contenedor uniproceso (STA
) o contenedor multiproceso (MTA
)).
Ejemplos
En el ejemplo de código siguiente se muestra cómo establecer el estado de apartamento de un subproceso.
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.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(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);
}
}
open System.Threading
let threadMethod () = Thread.Sleep 1000
let newThread = Thread threadMethod
newThread.SetApartmentState ApartmentState.MTA
printfn $"ThreadState: {newThread.ThreadState}, ApartmentState: {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
with :? ThreadStateException as stateException ->
printfn $"\n{stateException.GetType().Name} caught:\nThread is not in the Unstarted or Running state."
printfn $"ThreadState: {newThread.ThreadState}, ApartmentState: {newThread.GetApartmentState()}"
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
Comentarios
La propiedad ApartmentState está obsoleta. Las alternativas no obsoletas son el GetApartmentState método para recuperar el estado del apartamento y el SetApartmentState método para establecer el estado del apartamento.
En las versiones 1.0 y 1.1 de .NET Framework, la ApartmentState
propiedad marca un subproceso para indicar que se ejecutará en un contenedor multiproceso o multiproceso. Esta propiedad se puede establecer cuando el subproceso está en estado Unstarted
de subproceso o Running
; sin embargo, solo se puede establecer una vez para un subproceso. Si no se ha establecido la propiedad , devuelve Unknown
.
Intento de usar la ApartmentState propiedad para establecer el estado del apartamento de un subproceso cuyo estado de apartamento ya se ha establecido se omite. Sin embargo, el SetApartmentState método produce un InvalidOperationException en este caso.
Importante
En .NET Framework versión 2.0, los nuevos subprocesos se inicializan como ApartmentState.MTA si no se hubiera establecido su estado de apartamento antes de iniciarse. El subproceso de aplicación principal se inicializa de ApartmentState.MTA forma predeterminada. Ya no puede establecer el subproceso ApartmentState.STA de aplicación principal en estableciendo la System.Threading.ApartmentState propiedad en la primera línea de código. Use STAThreadAttribute en su lugar.
En .NET Framework versión 2.0, puede especificar el modelo de subprocesos COM para una aplicación de C++ mediante la opción del vinculador /CLRTHREADATTRIBUTE (Establecer atributo de subproceso CLR).