Monitor.Enter メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
指定したオブジェクトの排他ロックを取得します。
オーバーロード
| 名前 | 説明 |
|---|---|
| Enter(Object) |
指定したオブジェクトの排他ロックを取得します。 |
| Enter(Object, Boolean) |
指定したオブジェクトの排他ロックを取得し、ロックが取得されたかどうかを示す値をアトミックに設定します。 |
Enter(Object)
- ソース:
- Monitor.cs
- ソース:
- Monitor.cs
- ソース:
- Monitor.cs
指定したオブジェクトの排他ロックを取得します。
public:
static void Enter(System::Object ^ obj);
public static void Enter(object obj);
static member Enter : obj -> unit
Public Shared Sub Enter (obj As Object)
パラメーター
- obj
- Object
モニター ロックを取得するオブジェクト。
例外
obj パラメーターはnull。
例
次の例では、 Enter メソッドの使用方法を示します。
using System;
using System.Threading;
using System.Collections.Generic;
using System.Text;
class SafeQueue<T>
{
// A queue that is protected by Monitor.
private Queue<T> m_inputQueue = new Queue<T>();
// Lock the queue and add an element.
public void Enqueue(T qValue)
{
// Request the lock, and block until it is obtained.
Monitor.Enter(m_inputQueue);
try
{
// When the lock is obtained, add an element.
m_inputQueue.Enqueue(qValue);
}
finally
{
// Ensure that the lock is released.
Monitor.Exit(m_inputQueue);
}
}
// Try to add an element to the queue: Add the element to the queue
// only if the lock is immediately available.
public bool TryEnqueue(T qValue)
{
// Request the lock.
if (Monitor.TryEnter(m_inputQueue))
{
try
{
m_inputQueue.Enqueue(qValue);
}
finally
{
// Ensure that the lock is released.
Monitor.Exit(m_inputQueue);
}
return true;
}
else
{
return false;
}
}
// Try to add an element to the queue: Add the element to the queue
// only if the lock becomes available during the specified time
// interval.
public bool TryEnqueue(T qValue, int waitTime)
{
// Request the lock.
if (Monitor.TryEnter(m_inputQueue, waitTime))
{
try
{
m_inputQueue.Enqueue(qValue);
}
finally
{
// Ensure that the lock is released.
Monitor.Exit(m_inputQueue);
}
return true;
}
else
{
return false;
}
}
// Lock the queue and dequeue an element.
public T Dequeue()
{
T retval;
// Request the lock, and block until it is obtained.
Monitor.Enter(m_inputQueue);
try
{
// When the lock is obtained, dequeue an element.
retval = m_inputQueue.Dequeue();
}
finally
{
// Ensure that the lock is released.
Monitor.Exit(m_inputQueue);
}
return retval;
}
// Delete all elements that equal the given object.
public int Remove(T qValue)
{
int removedCt = 0;
// Wait until the lock is available and lock the queue.
Monitor.Enter(m_inputQueue);
try
{
int counter = m_inputQueue.Count;
while (counter > 0)
// Check each element.
{
T elem = m_inputQueue.Dequeue();
if (!elem.Equals(qValue))
{
m_inputQueue.Enqueue(elem);
}
else
{
// Keep a count of items removed.
removedCt += 1;
}
counter = counter - 1;
}
}
finally
{
// Ensure that the lock is released.
Monitor.Exit(m_inputQueue);
}
return removedCt;
}
// Print all queue elements.
public string PrintAllElements()
{
StringBuilder output = new StringBuilder();
// Lock the queue.
Monitor.Enter(m_inputQueue);
try
{
foreach( T elem in m_inputQueue )
{
// Print the next element.
output.AppendLine(elem.ToString());
}
}
finally
{
// Ensure that the lock is released.
Monitor.Exit(m_inputQueue);
}
return output.ToString();
}
}
public class Example
{
private static SafeQueue<int> q = new SafeQueue<int>();
private static int threadsRunning = 0;
private static int[][] results = new int[3][];
static void Main()
{
Console.WriteLine("Working...");
for(int i = 0; i < 3; i++)
{
Thread t = new Thread(ThreadProc);
t.Start(i);
Interlocked.Increment(ref threadsRunning);
}
}
private static void ThreadProc(object state)
{
DateTime finish = DateTime.Now.AddSeconds(10);
Random rand = new Random();
int[] result = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int threadNum = (int) state;
while (DateTime.Now < finish)
{
int what = rand.Next(250);
int how = rand.Next(100);
if (how < 16)
{
q.Enqueue(what);
result[(int)ThreadResultIndex.EnqueueCt] += 1;
}
else if (how < 32)
{
if (q.TryEnqueue(what))
{
result[(int)ThreadResultIndex.TryEnqueueSucceedCt] += 1;
}
else
{
result[(int)ThreadResultIndex.TryEnqueueFailCt] += 1;
}
}
else if (how < 48)
{
// Even a very small wait significantly increases the success
// rate of the conditional enqueue operation.
if (q.TryEnqueue(what, 10))
{
result[(int)ThreadResultIndex.TryEnqueueWaitSucceedCt] += 1;
}
else
{
result[(int)ThreadResultIndex.TryEnqueueWaitFailCt] += 1;
}
}
else if (how < 96)
{
result[(int)ThreadResultIndex.DequeueCt] += 1;
try
{
q.Dequeue();
}
catch
{
result[(int)ThreadResultIndex.DequeueExCt] += 1;
}
}
else
{
result[(int)ThreadResultIndex.RemoveCt] += 1;
result[(int)ThreadResultIndex.RemovedCt] += q.Remove(what);
}
}
results[threadNum] = result;
if (0 == Interlocked.Decrement(ref threadsRunning))
{
StringBuilder sb = new StringBuilder(
" Thread 1 Thread 2 Thread 3 Total\n");
for(int row = 0; row < 9; row++)
{
int total = 0;
sb.Append(titles[row]);
for(int col = 0; col < 3; col++)
{
sb.Append(String.Format("{0,9}", results[col][row]));
total += results[col][row];
}
sb.AppendLine(String.Format("{0,9}", total));
}
Console.WriteLine(sb.ToString());
}
}
private static string[] titles = {
"Enqueue ",
"TryEnqueue succeeded ",
"TryEnqueue failed ",
"TryEnqueue(T, wait) succeeded ",
"TryEnqueue(T, wait) failed ",
"Dequeue attempts ",
"Dequeue exceptions ",
"Remove operations ",
"Queue elements removed "};
private enum ThreadResultIndex
{
EnqueueCt,
TryEnqueueSucceedCt,
TryEnqueueFailCt,
TryEnqueueWaitSucceedCt,
TryEnqueueWaitFailCt,
DequeueCt,
DequeueExCt,
RemoveCt,
RemovedCt
};
}
/* This example produces output similar to the following:
Working...
Thread 1 Thread 2 Thread 3 Total
Enqueue 277382 515209 308464 1101055
TryEnqueue succeeded 276873 514621 308099 1099593
TryEnqueue failed 109 181 134 424
TryEnqueue(T, wait) succeeded 276913 514434 307607 1098954
TryEnqueue(T, wait) failed 2 0 0 2
Dequeue attempts 830980 1544081 924164 3299225
Dequeue exceptions 12102 21589 13539 47230
Remove operations 69550 129479 77351 276380
Queue elements removed 11957 22572 13043 47572
*/
Imports System.Threading
Imports System.Collections.Generic
Imports System.Text
Class SafeQueue(Of T)
' A queue that is protected by Monitor.
Private m_inputQueue As New Queue(Of T)
' Lock the queue and add an element.
Public Sub Enqueue(ByVal qValue As T)
' Request the lock, and block until it is obtained.
Monitor.Enter(m_inputQueue)
Try
' When the lock is obtained, add an element.
m_inputQueue.Enqueue(qValue)
Finally
' Ensure that the lock is released.
Monitor.Exit(m_inputQueue)
End Try
End Sub
' Try to add an element to the queue: Add the element to the queue
' only if the lock is immediately available.
Public Function TryEnqueue(ByVal qValue As T) As Boolean
' Request the lock.
If Monitor.TryEnter(m_inputQueue) Then
Try
m_inputQueue.Enqueue(qValue)
Finally
' Ensure that the lock is released.
Monitor.Exit(m_inputQueue)
End Try
Return True
Else
Return False
End If
End Function
' Try to add an element to the queue: Add the element to the queue
' only if the lock becomes available during the specified time
' interval.
Public Function TryEnqueue(ByVal qValue As T, ByVal waitTime As Integer) As Boolean
' Request the lock.
If Monitor.TryEnter(m_inputQueue, waitTime) Then
Try
m_inputQueue.Enqueue(qValue)
Finally
' Ensure that the lock is released.
Monitor.Exit(m_inputQueue)
End Try
Return True
Else
Return False
End If
End Function
' Lock the queue and dequeue an element.
Public Function Dequeue() As T
Dim retval As T
' Request the lock, and block until it is obtained.
Monitor.Enter(m_inputQueue)
Try
' When the lock is obtained, dequeue an element.
retval = m_inputQueue.Dequeue()
Finally
' Ensure that the lock is released.
Monitor.Exit(m_inputQueue)
End Try
Return retval
End Function
' Delete all elements that equal the given object.
Public Function Remove(ByVal qValue As T) As Integer
Dim removedCt As Integer = 0
' Wait until the lock is available and lock the queue.
Monitor.Enter(m_inputQueue)
Try
Dim counter As Integer = m_inputQueue.Count
While (counter > 0)
'Check each element.
Dim elem As T = m_inputQueue.Dequeue()
If Not elem.Equals(qValue) Then
m_inputQueue.Enqueue(elem)
Else
' Keep a count of items removed.
removedCt += 1
End If
counter = counter - 1
End While
Finally
' Ensure that the lock is released.
Monitor.Exit(m_inputQueue)
End Try
Return removedCt
End Function
' Print all queue elements.
Public Function PrintAllElements() As String
Dim output As New StringBuilder()
'Lock the queue.
Monitor.Enter(m_inputQueue)
Try
For Each elem As T In m_inputQueue
' Print the next element.
output.AppendLine(elem.ToString())
Next
Finally
' Ensure that the lock is released.
Monitor.Exit(m_inputQueue)
End Try
Return output.ToString()
End Function
End Class
Public Class Example
Private Shared q As New SafeQueue(Of Integer)
Private Shared threadsRunning As Integer = 0
Private Shared results(2)() As Integer
Friend Shared Sub Main()
Console.WriteLine("Working...")
For i As Integer = 0 To 2
Dim t As New Thread(AddressOf ThreadProc)
t.Start(i)
Interlocked.Increment(threadsRunning)
Next i
End Sub
Private Shared Sub ThreadProc(ByVal state As Object)
Dim finish As DateTime = DateTime.Now.AddSeconds(10)
Dim rand As New Random()
Dim result() As Integer = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
Dim threadNum As Integer = CInt(state)
While (DateTime.Now < finish)
Dim what As Integer = rand.Next(250)
Dim how As Integer = rand.Next(100)
If how < 16 Then
q.Enqueue(what)
result(ThreadResultIndex.EnqueueCt) += 1
Else If how < 32 Then
If q.TryEnqueue(what)
result(ThreadResultIndex.TryEnqueueSucceedCt) += 1
Else
result(ThreadResultIndex.TryEnqueueFailCt) += 1
End If
Else If how < 48 Then
' Even a very small wait significantly increases the success
' rate of the conditional enqueue operation.
If q.TryEnqueue(what, 10)
result(ThreadResultIndex.TryEnqueueWaitSucceedCt) += 1
Else
result(ThreadResultIndex.TryEnqueueWaitFailCt) += 1
End If
Else If how < 96 Then
result(ThreadResultIndex.DequeueCt) += 1
Try
q.Dequeue()
Catch
result(ThreadResultIndex.DequeueExCt) += 1
End Try
Else
result(ThreadResultIndex.RemoveCt) += 1
result(ThreadResultIndex.RemovedCt) += q.Remove(what)
End If
End While
results(threadNum) = result
If 0 = Interlocked.Decrement(threadsRunning) Then
Dim sb As New StringBuilder( _
" Thread 1 Thread 2 Thread 3 Total" & vbLf)
For row As Integer = 0 To 8
Dim total As Integer = 0
sb.Append(titles(row))
For col As Integer = 0 To 2
sb.Append(String.Format("{0,9}", results(col)(row)))
total += results(col)(row)
Next col
sb.AppendLine(String.Format("{0,9}", total))
Next row
Console.WriteLine(sb.ToString())
End If
End Sub
Private Shared titles() As String = { _
"Enqueue ", _
"TryEnqueue succeeded ", _
"TryEnqueue failed ", _
"TryEnqueue(T, wait) succeeded ", _
"TryEnqueue(T, wait) failed ", _
"Dequeue attempts ", _
"Dequeue exceptions ", _
"Remove operations ", _
"Queue elements removed " _
}
Private Enum ThreadResultIndex
EnqueueCt
TryEnqueueSucceedCt
TryEnqueueFailCt
TryEnqueueWaitSucceedCt
TryEnqueueWaitFailCt
DequeueCt
DequeueExCt
RemoveCt
RemovedCt
End Enum
End Class
' This example produces output similar to the following:
'
'Working...
' Thread 1 Thread 2 Thread 3 Total
'Enqueue 294357 512164 302838 1109359
'TryEnqueue succeeded 294486 512403 303117 1110006
'TryEnqueue failed 108 234 127 469
'TryEnqueue(T, wait) succeeded 294259 512796 302556 1109611
'TryEnqueue(T, wait) failed 1 1 1 3
'Dequeue attempts 882266 1537993 907795 3328054
'Dequeue exceptions 12691 21474 13480 47645
'Remove operations 74059 128715 76187 278961
'Queue elements removed 12667 22606 13219 48492
注釈
パラメーターとして渡されたオブジェクトのMonitorを取得するには、Enterを使用します。 別のスレッドがオブジェクトに対して Enter を実行したが、対応する Exitをまだ実行していない場合、現在のスレッドは、他のスレッドがオブジェクトを解放するまでブロックされます。 ブロックせずに同じスレッドが Enter を複数回呼び出すのは有効ですが、オブジェクトを待機している他のスレッドがブロックを解除する前に、同じ数の Exit 呼び出しを呼び出す必要があります。
Monitorを使用して、値型ではなくオブジェクト (つまり、参照型) をロックします。
Enterに値型変数を渡すと、オブジェクトとしてボックス化されます。 同じ変数を再び Enter 渡すと、別のオブジェクトとしてボックス化され、スレッドはブロックされません。 この場合、 Monitor が保護していると思われるコードは保護されません。 さらに、変数を Exitに渡すと、さらに別のオブジェクトが作成されます。
Exitに渡されるオブジェクトは、Enterに渡されるオブジェクトとは異なるため、MonitorはSynchronizationLockExceptionをスローします。 詳細については、概念に関するトピック 「モニター」を参照してください。
Interrupt は、オブジェクトに対する Monitor の入力を待機しているスレッドを中断できます。
ThreadInterruptedExceptionがスローされます。
C# tryを使用します...
finally ブロック (Try...Finally in Visual Basic) を使用してモニターを解放するか、C# lock ステートメント (Visual Basic の SyncLock ステートメント) を使用します。これにより、Enter および Exit メソッドが try... でラップされます。
finally ブロック。
こちらもご覧ください
適用対象
Enter(Object, Boolean)
- ソース:
- Monitor.cs
指定したオブジェクトの排他ロックを取得し、ロックが取得されたかどうかを示す値をアトミックに設定します。
public:
static void Enter(System::Object ^ obj, bool % lockTaken);
public static void Enter(object obj, ref bool lockTaken);
static member Enter : obj * bool -> unit
Public Shared Sub Enter (obj As Object, ByRef lockTaken As Boolean)
パラメーター
- obj
- Object
待機するオブジェクト。
- lockTaken
- Boolean
参照渡しでロックを取得しようとした結果。 入力は falseする必要があります。 ロックが取得された場合、出力は true されます。それ以外の場合、出力は false。 ロックの取得中に例外が発生した場合でも、出力が設定されます。
注: 例外が発生しない場合、このメソッドの出力は常に true。
例外
lockTakenへの入力はtrue。
obj パラメーターはnull。
例
次のコードは、 Enter(Object, Boolean) メソッドのオーバーロードを使用するための基本的なパターンを示しています。 このオーバーロードは常に、メソッドが例外をスローした場合でも、ref パラメーター (Visual Basic の ByRef) lockTaken に渡される変数の値を設定するため、変数の値はロックを解放する必要があるかどうかを確実にテストできます。
bool acquiredLock = false;
try
{
Monitor.Enter(lockObject, ref acquiredLock);
// Code that accesses resources that are protected by the lock.
}
finally
{
if (acquiredLock)
{
Monitor.Exit(lockObject);
}
}
Dim acquiredLock As Boolean = False
Try
Monitor.Enter(lockObject, acquiredLock)
' Code that accesses resources that are protected by the lock.
Finally
If acquiredLock Then
Monitor.Exit(lockObject)
End If
End Try
注釈
Enterを使用して、obj パラメーターとして渡されたオブジェクトのMonitorを取得します。 別のスレッドがオブジェクトに対して Enter を実行したが、対応する Exitをまだ実行していない場合、現在のスレッドは、他のスレッドがオブジェクトを解放するまでブロックされます。 ブロックせずに同じスレッドが Enter を複数回呼び出すのは有効ですが、オブジェクトを待機している他のスレッドがブロックを解除する前に、同じ数の Exit 呼び出しを呼び出す必要があります。
例外がスローされたためにロックが解除された場合、 lockTaken パラメーターに指定された変数は、このメソッドの終了後に false されます。 これにより、プログラムは、ロックを解除する必要があるかどうかをすべての場合に判断できます。 このメソッドが例外をスローせずに戻った場合、 lockTaken パラメーターに指定された変数は常に trueされ、テストする必要はありません。
Monitorを使用して、値型ではなくオブジェクト (つまり、参照型) をロックします。
Enterに値型変数を渡すと、オブジェクトとしてボックス化されます。 同じ変数を再び Enter 渡すと、別のオブジェクトとしてボックス化され、スレッドはブロックされません。 この場合、 Monitor が保護していると思われるコードは保護されません。 さらに、変数を Exitに渡すと、別の個別のオブジェクトが作成されます。
Exitに渡されるオブジェクトは、Enterに渡されるオブジェクトとは異なるため、MonitorはSynchronizationLockExceptionをスローします。 詳細については、概念に関するトピック 「モニター」を参照してください。
Interrupt は、オブジェクトに対する Monitor の入力を待機しているスレッドを中断できます。
ThreadInterruptedExceptionがスローされます。