ReaderWriterLock.AcquireWriterLock Método
Definição
Adquire o bloqueio de gravador.Acquires the writer lock.
Sobrecargas
| AcquireWriterLock(Int32) |
Adquire um bloqueio de gravador, usando um valor Int32 para o tempo limite.Acquires the writer lock, using an Int32 value for the time-out. |
| AcquireWriterLock(TimeSpan) |
Adquire um bloqueio de gravador, usando um valor TimeSpan para o tempo limite.Acquires the writer lock, using a TimeSpan value for the time-out. |
AcquireWriterLock(Int32)
public:
void AcquireWriterLock(int millisecondsTimeout);
public void AcquireWriterLock (int millisecondsTimeout);
member this.AcquireWriterLock : int -> unit
Public Sub AcquireWriterLock (millisecondsTimeout As Integer)
Parâmetros
- millisecondsTimeout
- Int32
O tempo limite em milissegundos.The time-out in milliseconds.
Exceções
O timeout expira antes que a solicitação de bloqueio seja concedida.timeout expires before the lock request is granted.
Exemplos
O exemplo de código a seguir mostra como adquirir e liberar um bloqueio de gravador e como tratar a exceção lançada quando uma solicitação atinge o tempo limite.The following code example shows how to acquire and release a writer lock, and how to handle the exception thrown when a request times out.
Esse código é parte de um exemplo maior fornecido para a ReaderWriterLock classe.This code is part of a larger example provided for the ReaderWriterLock class.
// The complete code is located in the ReaderWriterLock
// class topic.
using namespace System;
using namespace System::Threading;
public ref class Test
{
public:
// Declaring the ReaderWriterLock at the class level
// makes it visible to all threads.
static ReaderWriterLock^ rwl = gcnew ReaderWriterLock;
// For this example, the shared resource protected by the
// ReaderWriterLock is just an integer.
static int resource = 0;
// The complete code is located in the ReaderWriterLock class topic.
using System;
using System.Threading;
public class Example
{
static ReaderWriterLock rwl = new ReaderWriterLock();
// Define the shared resource protected by the ReaderWriterLock.
static int resource = 0;
' The complete code is located in the ReaderWriterLock class topic.
Imports System.Threading
Public Module Example
Private rwl As New ReaderWriterLock()
' Define the shared resource protected by the ReaderWriterLock.
Private resource As Integer = 0
// Shows how to request and release the writer lock, and
// how to handle time-outs.
static void WriteToResource( Random^ rnd, int timeOut )
{
try
{
rwl->AcquireWriterLock( timeOut );
try
{
// It is safe for this thread to read or write
// from the shared resource.
resource = rnd->Next( 500 );
Display( String::Format( "writes resource value {0}", resource ) );
Interlocked::Increment( writes );
}
finally
{
// Ensure that the lock is released.
rwl->ReleaseWriterLock();
}
}
catch ( ApplicationException^ )
{
// The writer lock request timed out.
Interlocked::Increment( writerTimeouts );
}
}
// Request and release the writer lock, and handle time-outs.
static void WriteToResource(Random rnd, int timeOut)
{
try {
rwl.AcquireWriterLock(timeOut);
try {
// It's safe for this thread to access from the shared resource.
resource = rnd.Next(500);
Display("writes resource value " + resource);
Interlocked.Increment(ref writes);
}
finally {
// Ensure that the lock is released.
rwl.ReleaseWriterLock();
}
}
catch (ApplicationException) {
// The writer lock request timed out.
Interlocked.Increment(ref writerTimeouts);
}
}
' Request and release the writer lock, and handle time-outs.
Sub WriteToResource(rnd As Random, timeOut As Integer)
Try
rwl.AcquireWriterLock(timeOut)
Try
' It's safe for this thread to read or write from the shared resource.
resource = rnd.Next(500)
Display("writes resource value " & resource)
Interlocked.Increment(writes)
Finally
' Ensure that the lock is released.
rwl.ReleaseWriterLock()
End Try
Catch ex As ApplicationException
' The writer lock request timed out.
Interlocked.Increment(writerTimeouts)
End Try
End Sub
};
}
End Module
Comentários
Esse método bloqueará se outro thread tiver um bloqueio de leitor ou de gravador.This method blocks if another thread has a reader lock or writer lock. Para obter uma descrição da maneira como o gravador bloqueia as alternativas com vários bloqueios de leitor simultâneos, consulte a ReaderWriterLock classe.For a description of the way the writer lock alternates with multiple concurrent reader locks, see the ReaderWriterLock class.
Um thread que já tem um bloqueio de leitor pode adquirir o bloqueio do gravador de uma das duas maneiras: liberando o bloqueio do leitor antes de chamar AcquireWriterLock ou chamando UpgradeToWriterLock .A thread that already has a reader lock can acquire the writer lock in one of two ways: by releasing the reader lock before calling AcquireWriterLock, or by calling UpgradeToWriterLock.
Cuidado
Se um thread chamar AcquireWriterLock enquanto ainda tem um bloqueio de leitor, ele bloqueará seu próprio bloqueio de leitor; se um tempo limite infinito for especificado, o thread será bloqueado.If a thread calls AcquireWriterLock while it still has a reader lock, it will block on its own reader lock; if an infinite time-out is specified, the thread will deadlock. Para evitar esses deadlocks, use IsReaderLockHeld para determinar se o thread atual já tem um bloqueio de leitor.To avoid such deadlocks, use IsReaderLockHeld to determine whether the current thread already has a reader lock.
AcquireWriterLock dá suporte a solicitações recursivas de bloqueio de gravador.AcquireWriterLock supports recursive writer-lock requests. Ou seja, um thread pode chamar AcquireWriterLock várias vezes, o que incrementa a contagem de bloqueios a cada vez.That is, a thread can call AcquireWriterLock multiple times, which increments the lock count each time. Você deve chamar ReleaseWriterLock uma vez para cada vez que chamar AcquireWriterLock .You must call ReleaseWriterLock once for each time you call AcquireWriterLock. Como alternativa, você pode chamar ReleaseLock para reduzir a contagem de bloqueios para zero imediatamente.Alternatively, you can call ReleaseLock to reduce the lock count to zero immediately.
Solicitações de bloqueio recursiva são sempre concedidas imediatamente, sem colocar o thread solicitante na fila do gravador.Recursive lock requests are always granted immediately, without placing the requesting thread in the writer queue.
Para obter valores de tempo limite válidos, consulte ReaderWriterLock .For valid time-out values, see ReaderWriterLock.
Aplica-se a
AcquireWriterLock(TimeSpan)
public:
void AcquireWriterLock(TimeSpan timeout);
public void AcquireWriterLock (TimeSpan timeout);
member this.AcquireWriterLock : TimeSpan -> unit
Public Sub AcquireWriterLock (timeout As TimeSpan)
Parâmetros
- timeout
- TimeSpan
O TimeSpan que especifica o período de tempo limite.The TimeSpan specifying the time-out period.
Exceções
O timeout expira antes que a solicitação de bloqueio seja concedida.timeout expires before the lock request is granted.
timeout especifica um valor negativo diferente de -1 milissegundo.timeout specifies a negative value other than -1 milliseconds.
Comentários
Esse método bloqueará se outro thread tiver um bloqueio de leitor ou de gravador.This method blocks if another thread has a reader lock or writer lock. Para obter uma descrição da maneira como o gravador bloqueia as alternativas com vários bloqueios de leitor simultâneos, consulte a ReaderWriterLock classe.For a description of the way the writer lock alternates with multiple concurrent reader locks, see the ReaderWriterLock class.
Um thread que já tem um bloqueio de leitor pode adquirir o bloqueio do gravador de uma das duas maneiras: liberando o bloqueio do leitor antes de chamar AcquireWriterLock ou chamando UpgradeToWriterLock .A thread that already has a reader lock can acquire the writer lock in one of two ways: by releasing the reader lock before calling AcquireWriterLock, or by calling UpgradeToWriterLock.
Cuidado
Se um thread chamar AcquireWriterLock enquanto ainda tem um bloqueio de leitor, ele bloqueará seu próprio bloqueio de leitor; se um tempo limite infinito for especificado, o thread será bloqueado.If a thread calls AcquireWriterLock while it still has a reader lock, it will block on its own reader lock; if an infinite time-out is specified, the thread will deadlock. Para evitar esses deadlocks, use IsReaderLockHeld para determinar se o thread atual já tem um bloqueio de leitor.To avoid such deadlocks, use IsReaderLockHeld to determine whether the current thread already has a reader lock.
AcquireWriterLock dá suporte a solicitações recursivas de bloqueio de gravador.AcquireWriterLock supports recursive writer-lock requests. Ou seja, um thread pode chamar AcquireWriterLock várias vezes, o que incrementa a contagem de bloqueios a cada vez.That is, a thread can call AcquireWriterLock multiple times, which increments the lock count each time. Você deve chamar ReleaseWriterLock uma vez para cada vez que chamar AcquireWriterLock .You must call ReleaseWriterLock once for each time you call AcquireWriterLock. Como alternativa, você pode chamar ReleaseLock para reduzir a contagem de bloqueios para zero imediatamente.Alternatively, you can call ReleaseLock to reduce the lock count to zero immediately.
Solicitações de bloqueio recursiva são sempre concedidas imediatamente, sem colocar o thread solicitante na fila do gravador.Recursive lock requests are always granted immediately, without placing the requesting thread in the writer queue.
Para obter valores de tempo limite válidos, consulte ReaderWriterLock .For valid time-out values, see ReaderWriterLock.