AbandonedMutexException Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
A exceção que é lançada quando um thread adquire um Mutex objeto que outro thread abandonou ao sair sem o libertar.
public ref class AbandonedMutexException : Exception
public ref class AbandonedMutexException : SystemException
public class AbandonedMutexException : Exception
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class AbandonedMutexException : SystemException
public class AbandonedMutexException : SystemException
type AbandonedMutexException = class
inherit Exception
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type AbandonedMutexException = class
inherit SystemException
type AbandonedMutexException = class
inherit SystemException
Public Class AbandonedMutexException
Inherits Exception
Public Class AbandonedMutexException
Inherits SystemException
- Herança
- Herança
- Atributos
Exemplos
O exemplo de código seguinte executa um thread que abandona cinco mutexes, demonstrando os seus efeitos nos WaitOnemétodos , WaitAny, e WaitAll . O valor da MutexIndex propriedade é exibido para a WaitAny chamada.
Note
A chamada ao WaitAny método é interrompida por um dos mutexes abandonados. O outro mutex abandonado ainda pode causar AbandonedMutexException um lançamento por métodos de espera subsequentes.
using System;
using System.Threading;
public class Example
{
private static ManualResetEvent _dummy = new ManualResetEvent(false);
private static Mutex _orphan1 = new Mutex();
private static Mutex _orphan2 = new Mutex();
private static Mutex _orphan3 = new Mutex();
private static Mutex _orphan4 = new Mutex();
private static Mutex _orphan5 = new Mutex();
[MTAThread]
public static void Main()
{
// Start a thread that takes all five mutexes, and then
// ends without releasing them.
//
Thread t = new Thread(new ThreadStart(AbandonMutex));
t.Start();
// Make sure the thread is finished.
t.Join();
// Wait on one of the abandoned mutexes. The WaitOne returns
// immediately, because its wait condition is satisfied by
// the abandoned mutex, but on return it throws
// AbandonedMutexException.
try
{
_orphan1.WaitOne();
Console.WriteLine("WaitOne succeeded.");
}
catch(AbandonedMutexException ex)
{
Console.WriteLine("Exception on return from WaitOne." +
"\r\n\tMessage: {0}", ex.Message);
}
finally
{
// Whether or not the exception was thrown, the current
// thread owns the mutex, and must release it.
//
_orphan1.ReleaseMutex();
}
// Create an array of wait handles, consisting of one
// ManualResetEvent and two mutexes, using two more of the
// abandoned mutexes.
WaitHandle[] waitFor = {_dummy, _orphan2, _orphan3};
// WaitAny returns when any of the wait handles in the
// array is signaled, so either of the two abandoned mutexes
// satisfy its wait condition. On returning from the wait,
// WaitAny throws AbandonedMutexException. The MutexIndex
// property returns the lower of the two index values for
// the abandoned mutexes. Note that the Try block and the
// Catch block obtain the index in different ways.
//
try
{
int index = WaitHandle.WaitAny(waitFor);
Console.WriteLine("WaitAny succeeded.");
// The current thread owns the mutex, and must release
// it.
Mutex m = waitFor[index] as Mutex;
if (m != null) m.ReleaseMutex();
}
catch(AbandonedMutexException ex)
{
Console.WriteLine("Exception on return from WaitAny at index {0}." +
"\r\n\tMessage: {1}", ex.MutexIndex, ex.Message);
// Whether or not the exception was thrown, the current
// thread owns the mutex, and must release it.
//
if (ex.Mutex != null) ex.Mutex.ReleaseMutex();
}
// Use two more of the abandoned mutexes for the WaitAll call.
// WaitAll doesn't return until all wait handles are signaled,
// so the ManualResetEvent must be signaled by calling Set().
_dummy.Set();
waitFor[1] = _orphan4;
waitFor[2] = _orphan5;
// The signaled event and the two abandoned mutexes satisfy
// the wait condition for WaitAll, but on return it throws
// AbandonedMutexException. For WaitAll, the MutexIndex
// property is always -1 and the Mutex property is always
// null.
//
try
{
WaitHandle.WaitAll(waitFor);
Console.WriteLine("WaitAll succeeded.");
}
catch(AbandonedMutexException ex)
{
Console.WriteLine("Exception on return from WaitAll. MutexIndex = {0}." +
"\r\n\tMessage: {1}", ex.MutexIndex, ex.Message);
}
finally
{
// Whether or not the exception was thrown, the current
// thread owns the mutexes, and must release them.
//
_orphan4.ReleaseMutex();
_orphan5.ReleaseMutex();
}
}
[MTAThread]
public static void AbandonMutex()
{
_orphan1.WaitOne();
_orphan2.WaitOne();
_orphan3.WaitOne();
_orphan4.WaitOne();
_orphan5.WaitOne();
// Abandon the mutexes by exiting without releasing them.
Console.WriteLine("Thread exits without releasing the mutexes.");
}
}
/* This code example produces the following output:
Thread exits without releasing the mutexes.
Exception on return from WaitOne.
Message: The wait completed due to an abandoned mutex.
Exception on return from WaitAny at index 1.
Message: The wait completed due to an abandoned mutex.
Exception on return from WaitAll. MutexIndex = -1.
Message: The wait completed due to an abandoned mutex.
*/
Option Explicit
Imports System.Threading
Public Class Example
Private Shared _dummy As New ManualResetEvent(False)
Private Shared _orphan1 As New Mutex()
Private Shared _orphan2 As New Mutex()
Private Shared _orphan3 As New Mutex()
Private Shared _orphan4 As New Mutex()
Private Shared _orphan5 As New Mutex()
<MTAThread> _
Public Shared Sub Main()
' Start a thread that takes all five mutexes, and then
' ends without releasing them.
'
Dim t As New Thread(AddressOf AbandonMutex)
t.Start()
' Make sure the thread is finished.
t.Join()
' Wait on one of the abandoned mutexes. The WaitOne returns
' immediately, because its wait condition is satisfied by
' the abandoned mutex, but on return it throws
' AbandonedMutexException.
Try
_orphan1.WaitOne()
Console.WriteLine("WaitOne succeeded.")
Catch ex As AbandonedMutexException
Console.WriteLine("Exception on return from WaitOne." _
& vbCrLf & vbTab & "Message: " _
& ex.Message)
Finally
' Whether or not the exception was thrown, the current
' thread owns the mutex, and must release it.
'
_orphan1.ReleaseMutex()
End Try
' Create an array of wait handles, consisting of one
' ManualResetEvent and two mutexes, using two more of the
' abandoned mutexes.
Dim waitFor(2) As WaitHandle
waitFor(0) = _dummy
waitFor(1) = _orphan2
waitFor(2) = _orphan3
' WaitAny returns when any of the wait handles in the
' array is signaled, so either of the two abandoned mutexes
' satisfy its wait condition. On returning from the wait,
' WaitAny throws AbandonedMutexException. The MutexIndex
' property returns the lower of the two index values for
' the abandoned mutexes. Note that the Try block and the
' Catch block obtain the index in different ways.
'
Try
Dim index As Integer = WaitHandle.WaitAny(waitFor)
Console.WriteLine("WaitAny succeeded.")
Dim m As Mutex = TryCast(waitFor(index), Mutex)
' The current thread owns the mutex, and must release
' it.
If m IsNot Nothing Then m.ReleaseMutex()
Catch ex As AbandonedMutexException
Console.WriteLine("Exception on return from WaitAny at index " _
& ex.MutexIndex & "." _
& vbCrLf & vbTab & "Message: " _
& ex.Message)
' Whether or not the exception was thrown, the current
' thread owns the mutex, and must release it.
'
If ex.Mutex IsNot Nothing Then ex.Mutex.ReleaseMutex()
End Try
' Use two more of the abandoned mutexes for the WaitAll call.
' WaitAll doesn't return until all wait handles are signaled,
' so the ManualResetEvent must be signaled by calling Set().
_dummy.Set()
waitFor(1) = _orphan4
waitFor(2) = _orphan5
' The signaled event and the two abandoned mutexes satisfy
' the wait condition for WaitAll, but on return it throws
' AbandonedMutexException. For WaitAll, the MutexIndex
' property is always -1 and the Mutex property is always
' Nothing.
'
Try
WaitHandle.WaitAll(waitFor)
Console.WriteLine("WaitAll succeeded.")
Catch ex As AbandonedMutexException
Console.WriteLine("Exception on return from WaitAll. MutexIndex = " _
& ex.MutexIndex & "." _
& vbCrLf & vbTab & "Message: " _
& ex.Message)
Finally
' Whether or not the exception was thrown, the current
' thread owns the mutexes, and must release them.
'
CType(waitFor(1), Mutex).ReleaseMutex()
CType(waitFor(2), Mutex).ReleaseMutex()
End Try
End Sub
<MTAThread> _
Public Shared Sub AbandonMutex()
_orphan1.WaitOne()
_orphan2.WaitOne()
_orphan3.WaitOne()
_orphan4.WaitOne()
_orphan5.WaitOne()
' Abandon the mutexes by exiting without releasing them.
Console.WriteLine("Thread exits without releasing the mutexes.")
End Sub
End Class
' This code example produces the following output:
'
'Thread exits without releasing the mutexes.
'Exception on return from WaitOne.
' Message: The wait completed due to an abandoned mutex.
'Exception on return from WaitAny at index 1.
' Message: The wait completed due to an abandoned mutex.
'Exception on return from WaitAll. MutexIndex = -1.
' Message: The wait completed due to an abandoned mutex.
Observações
Quando um thread abandona um mutex, a exceção é lançada no thread seguinte que adquire o mutex. O tópico pode adquirir o mutex porque já estava à espera do mutex ou porque este entra no mutex mais tarde.
Um mutex abandonado indica um erro grave de programação. Quando um thread sai sem libertar o mutex, as estruturas de dados protegidas pelo mutex podem não estar num estado consistente. Antes da versão 2.0 do .NET Framework, tais problemas eram difíceis de detetar porque não era feita exceção se uma espera fosse concluída devido a um mutex abandonado. Para obter mais informações, consulte a classe Mutex.
O próximo tópico a solicitar a propriedade do mutex pode tratar desta exceção e prosseguir, desde que a integridade das estruturas de dados possa ser verificada.
Construtores
| Name | Description |
|---|---|
| AbandonedMutexException() |
Inicializa uma nova instância da AbandonedMutexException classe com valores por defeito. |
| AbandonedMutexException(Int32, WaitHandle) |
Inicializa uma nova instância da AbandonedMutexException classe com um índice especificado para o mutex abandonado, se aplicável, e um Mutex objeto que representa o mutex. |
| AbandonedMutexException(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da AbandonedMutexException classe com dados serializados. |
| AbandonedMutexException(String, Exception, Int32, WaitHandle) |
Inicializa uma nova instância da AbandonedMutexException classe com uma mensagem de erro especificada, a exceção interna, o índice para o mutex abandonado, se aplicável, e um Mutex objeto que representa o mutex. |
| AbandonedMutexException(String, Exception) |
Inicializa uma nova instância da AbandonedMutexException classe com uma mensagem de erro especificada e uma exceção interna. |
| AbandonedMutexException(String, Int32, WaitHandle) |
Inicializa uma nova instância da AbandonedMutexException classe com uma mensagem de erro especificada, o índice do mutex abandonado, se aplicável, e o mutex abandonado. |
| AbandonedMutexException(String) |
Inicializa uma nova instância da AbandonedMutexException classe com uma mensagem de erro especificada. |
Propriedades
| Name | Description |
|---|---|
| Data |
Obtém uma coleção de pares chave/valor que fornecem informação adicional definida pelo utilizador sobre a exceção. (Herdado de Exception) |
| HelpLink |
Obtém ou define um link para o ficheiro de ajuda associado a esta exceção. (Herdado de Exception) |
| HResult |
Recebe ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica. (Herdado de Exception) |
| InnerException |
Obtém a Exception instância que causou a exceção atual. (Herdado de Exception) |
| Message |
Recebe uma mensagem que descreve a exceção atual. (Herdado de Exception) |
| Mutex |
Fica com o mutex abandonado que causou a exceção, se souber. |
| MutexIndex |
Obtém o índice do mutex abandonado que causou a exceção, se for conhecido. |
| Source |
Obtém ou define o nome do aplicativo ou o objeto que causa o erro. (Herdado de Exception) |
| StackTrace |
Obtém uma representação string dos frames imediatos na stack de chamadas. (Herdado de Exception) |
| TargetSite |
Obtém o método que lança a exceção atual. (Herdado de Exception) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetBaseException() |
Quando sobrescrito numa classe derivada, devolve o Exception que é a causa raiz de uma ou mais exceções subsequentes. (Herdado de Exception) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Quando sobreposto numa classe derivada, define a SerializationInfo informação com sobre a exceção. (Herdado de Exception) |
| GetType() |
Obtém o tipo de execução da instância atual. (Herdado de Exception) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Cria e devolve uma representação string da exceção atual. (Herdado de Exception) |
evento
| Name | Description |
|---|---|
| SerializeObjectState |
Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção. (Herdado de Exception) |