WaitHandle.WaitOne 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
현재 WaitHandle이(가) 신호를 받을 때까지 현재 스레드를 차단합니다.
오버로드
WaitOne() |
현재 WaitHandle이(가) 신호를 받을 때까지 현재 스레드를 차단합니다. |
WaitOne(Int32) |
부호 있는 32비트 정수로 시간 간격(밀리초)을 지정하여 현재 WaitHandle이 신호를 받을 때까지 현재 스레드를 차단합니다. |
WaitOne(TimeSpan) |
TimeSpan로 시간 간격을 지정하여 현재 인스턴스가 신호를 받을 때까지 현재 스레드를 차단합니다. |
WaitOne(Int32, Boolean) |
부호 있는 32비트 정수로 시간 간격을 지정하고 대기 전에 동기화 도메인을 끝낼지 여부를 지정하여 현재 WaitHandle이 신호를 받을 때까지 현재 스레드를 차단합니다. |
WaitOne(TimeSpan, Boolean) |
TimeSpan로 시간 간격을 지정하고 대기 전에 동기화 도메인을 끝낼지 여부를 지정하여 현재 인스턴스가 신호를 받을 때까지 현재 스레드를 차단합니다. |
WaitOne()
현재 WaitHandle이(가) 신호를 받을 때까지 현재 스레드를 차단합니다.
public:
virtual bool WaitOne();
public virtual bool WaitOne ();
abstract member WaitOne : unit -> bool
override this.WaitOne : unit -> bool
Public Overridable Function WaitOne () As Boolean
반환
현재 인스턴스가 신호를 받으면 true
를 반환합니다. 현재 인스턴스가 신호를 받지 않으면 WaitOne()은(는) 아무 값도 반환하지 않습니다.
예외
현재 인스턴스가 이미 삭제된 경우
스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.
현재 인스턴스가 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시인 경우
예제
다음 코드 예제에서는 백그라운드 스레드의 실행이 완료되기를 기다리는 동안 프로세스가 종료되지 않도록 대기 핸들을 사용하는 방법을 보여줍니다.
using namespace System;
using namespace System::Threading;
ref class WaitOne
{
private:
WaitOne(){}
public:
static void WorkMethod( Object^ stateInfo )
{
Console::WriteLine( "Work starting." );
// Simulate time spent working.
Thread::Sleep( (gcnew Random)->Next( 100, 2000 ) );
// Signal that work is finished.
Console::WriteLine( "Work ending." );
dynamic_cast<AutoResetEvent^>(stateInfo)->Set();
}
};
int main()
{
Console::WriteLine( "Main starting." );
AutoResetEvent^ autoEvent = gcnew AutoResetEvent( false );
ThreadPool::QueueUserWorkItem( gcnew WaitCallback( &WaitOne::WorkMethod ), autoEvent );
// Wait for work method to signal.
autoEvent->WaitOne( );
Console::WriteLine( "Work method signaled.\nMain ending." );
}
using System;
using System.Threading;
class WaitOne
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main()
{
Console.WriteLine("Main starting.");
ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkMethod), autoEvent);
// Wait for work method to signal.
autoEvent.WaitOne();
Console.WriteLine("Work method signaled.\nMain ending.");
}
static void WorkMethod(object stateInfo)
{
Console.WriteLine("Work starting.");
// Simulate time spent working.
Thread.Sleep(new Random().Next(100, 2000));
// Signal that work is finished.
Console.WriteLine("Work ending.");
((AutoResetEvent)stateInfo).Set();
}
}
Imports System.Threading
Public Class WaitOne
Shared autoEvent As New AutoResetEvent(False)
<MTAThread> _
Shared Sub Main()
Console.WriteLine("Main starting.")
ThreadPool.QueueUserWorkItem(AddressOf WorkMethod, autoEvent)
' Wait for work method to signal.
autoEvent.WaitOne()
Console.WriteLine("Work method signaled.")
Console.WriteLine("Main ending.")
End Sub
Shared Sub WorkMethod(stateInfo As Object)
Console.WriteLine("Work starting.")
' Simulate time spent working.
Thread.Sleep(New Random().Next(100, 2000))
' Signal that work is finished.
Console.WriteLine("Work ending.")
CType(stateInfo, AutoResetEvent).Set()
End Sub
End Class
설명
AbandonedMutexException는 .NET Framework 버전 2.0의 새로운 버전입니다. 이전 버전에서 WaitOne 메서드는 true
뮤텍스가 중단될 때 를 반환합니다. 중단된 뮤텍스는 종종 심각한 코딩 오류를 나타냅니다. 시스템 차원 뮤텍스의 경우 (예를 들어 Windows 작업 관리자 사용)가 애플리케이션이 갑자기 종료 된 나타낼 수 있습니다. 예외에는 디버깅에 유용한 정보가 포함되어 있습니다.
이 메서드의 호출자는 현재 인스턴스가 신호를 받을 때까지 무기한 차단됩니다. 비동기 작업이 완료될 때 가 생성되는 등의 신호를 다른 스레드에서 받을 때까지 이 메서드를 사용하여 WaitHandle 차단합니다. 자세한 내용은 IAsyncResult 인터페이스를 참조하세요.
이 메서드 오버로드를 호출하는 것은 WaitOne(Int32, Boolean) 메서드 오버로드를 호출하고 첫 번째 매개 변수 및 두 번째 매개 변수에 대해 -1 또는 를 지정하는 것과 Timeout.Infinite false
같습니다.
파생된 클래스의 동작을 사용자 지정 하려면이 메서드를 재정의 합니다.
적용 대상
WaitOne(Int32)
부호 있는 32비트 정수로 시간 간격(밀리초)을 지정하여 현재 WaitHandle이 신호를 받을 때까지 현재 스레드를 차단합니다.
public:
virtual bool WaitOne(int millisecondsTimeout);
public virtual bool WaitOne (int millisecondsTimeout);
abstract member WaitOne : int -> bool
override this.WaitOne : int -> bool
Public Overridable Function WaitOne (millisecondsTimeout As Integer) As Boolean
매개 변수
반환
현재 인스턴스가 신호를 받으면 true
이고, 그렇지 않으면 false
입니다.
예외
현재 인스턴스가 이미 삭제된 경우
millisecondsTimeout
이 시간 제한 없음을 나타내는 -1 이외의 음수인 경우
스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.
현재 인스턴스가 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시인 경우
예제
다음 코드 예제에서는 백그라운드 스레드의 실행이 완료되기를 기다리는 동안 프로세스가 종료되지 않도록 대기 핸들을 사용하는 방법을 보여줍니다.
using namespace System;
using namespace System::Threading;
ref class WaitOne
{
private:
WaitOne(){}
public:
static void WorkMethod( Object^ stateInfo )
{
Console::WriteLine( "Work starting." );
// Simulate time spent working.
Thread::Sleep( (gcnew Random)->Next( 100, 2000 ) );
// Signal that work is finished.
Console::WriteLine( "Work ending." );
dynamic_cast<AutoResetEvent^>(stateInfo)->Set();
}
};
int main()
{
Console::WriteLine( "Main starting." );
AutoResetEvent^ autoEvent = gcnew AutoResetEvent( false );
ThreadPool::QueueUserWorkItem( gcnew WaitCallback( &WaitOne::WorkMethod ), autoEvent );
// Wait for work method to signal.
if ( autoEvent->WaitOne( 1000 ) )
{
Console::WriteLine( "Work method signaled." );
}
else
{
Console::WriteLine( "Timed out waiting for work "
"method to signal." );
}
Console::WriteLine( "Main ending." );
}
using System;
using System.Threading;
class WaitOne
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main()
{
Console.WriteLine("Main starting.");
ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkMethod), autoEvent);
// Wait for work method to signal.
if(autoEvent.WaitOne(1000))
{
Console.WriteLine("Work method signaled.");
}
else
{
Console.WriteLine("Timed out waiting for work " +
"method to signal.");
}
Console.WriteLine("Main ending.");
}
static void WorkMethod(object stateInfo)
{
Console.WriteLine("Work starting.");
// Simulate time spent working.
Thread.Sleep(new Random().Next(100, 2000));
// Signal that work is finished.
Console.WriteLine("Work ending.");
((AutoResetEvent)stateInfo).Set();
}
}
Imports System.Threading
Public Class WaitOne
Shared autoEvent As New AutoResetEvent(False)
<MTAThread> _
Shared Sub Main()
Console.WriteLine("Main starting.")
ThreadPool.QueueUserWorkItem(AddressOf WorkMethod, autoEvent)
' Wait for work method to signal.
If autoEvent.WaitOne(1000) Then
Console.WriteLine("Work method signaled.")
Else
Console.WriteLine("Timed out waiting for work " & _
"method to signal.")
End If
Console.WriteLine("Main ending.")
End Sub
Shared Sub WorkMethod(stateInfo As Object)
Console.WriteLine("Work starting.")
' Simulate time spent working.
Thread.Sleep(New Random().Next(100, 2000))
' Signal that work is finished.
Console.WriteLine("Work ending.")
CType(stateInfo, AutoResetEvent).Set()
End Sub
End Class
설명
millisecondsTimeout
가 0이면 메서드가 차단되지 않습니다. 대기 핸들의 상태를 테스트하고 즉시 반환합니다.
이 메서드의 호출자는 현재 인스턴스가 신호를 받거나 시간제한이 발생할 때까지 차단됩니다. 비동기 작업이 완료될 때 가 생성되는 등의 신호를 다른 스레드에서 받을 때까지 이 메서드를 사용하여 WaitHandle 차단합니다. 자세한 내용은 IAsyncResult 인터페이스를 참조하세요.
파생된 클래스의 동작을 사용자 지정 하려면이 메서드를 재정의 합니다.
이 메서드 오버로드를 호출하는 것은 WaitOne(Int32, Boolean) 오버로드를 호출하고 에 를 지정하는 것과 false
exitContext
같습니다.
적용 대상
WaitOne(TimeSpan)
TimeSpan로 시간 간격을 지정하여 현재 인스턴스가 신호를 받을 때까지 현재 스레드를 차단합니다.
public:
virtual bool WaitOne(TimeSpan timeout);
public virtual bool WaitOne (TimeSpan timeout);
abstract member WaitOne : TimeSpan -> bool
override this.WaitOne : TimeSpan -> bool
Public Overridable Function WaitOne (timeout As TimeSpan) As Boolean
매개 변수
반환
현재 인스턴스가 신호를 받으면 true
이고, 그렇지 않으면 false
입니다.
예외
현재 인스턴스가 이미 삭제된 경우
timeout
은 시간 제한이 없음을 나타내는 -1밀리초 이외의 음수입니다.
또는
timeout
가 MaxValue보다 큰 경우
스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.
현재 인스턴스가 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시인 경우
설명
timeout
가 0이면 메서드가 차단되지 않습니다. 대기 핸들의 상태를 테스트하고 즉시 반환합니다.
이 메서드의 호출자는 현재 인스턴스가 신호를 받거나 시간제한이 발생할 때까지 차단됩니다. 비동기 작업이 완료될 때 가 생성되는 등의 신호를 다른 스레드에서 받을 때까지 이 메서드를 사용하여 WaitHandle 차단합니다. 자세한 내용은 IAsyncResult 인터페이스를 참조하세요.
파생된 클래스의 동작을 사용자 지정 하려면이 메서드를 재정의 합니다.
의 timeout
최대값은 Int32.MaxValue 입니다.
이 메서드 오버로드를 호출하는 것은 WaitOne(TimeSpan, Boolean) 오버로드를 호출하고 에 를 지정하는 것과 false
exitContext
같습니다.
적용 대상
WaitOne(Int32, Boolean)
부호 있는 32비트 정수로 시간 간격을 지정하고 대기 전에 동기화 도메인을 끝낼지 여부를 지정하여 현재 WaitHandle이 신호를 받을 때까지 현재 스레드를 차단합니다.
public:
virtual bool WaitOne(int millisecondsTimeout, bool exitContext);
public virtual bool WaitOne (int millisecondsTimeout, bool exitContext);
abstract member WaitOne : int * bool -> bool
override this.WaitOne : int * bool -> bool
Public Overridable Function WaitOne (millisecondsTimeout As Integer, exitContext As Boolean) As Boolean
매개 변수
- exitContext
- Boolean
대기 전에 컨텍스트에 대한 동기화 도메인을 종료하고(동기화된 컨텍스트에 있는 경우) 이 도메인을 다시 가져오려면 true
이고, 그렇지 않으면 false
입니다.
반환
현재 인스턴스가 신호를 받으면 true
이고, 그렇지 않으면 false
입니다.
예외
현재 인스턴스가 이미 삭제된 경우
millisecondsTimeout
이 시간 제한 없음을 나타내는 -1 이외의 음수인 경우
스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.
현재 인스턴스가 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시인 경우
예제
다음 예제에서는 메서드 오버 로드가 동기화 도메인 내에서 호출 될 때 동작 하는 방법을 보여 WaitOne(Int32, Boolean) 있습니다. 첫째, 스레드는 로 설정된 를 exitContext
사용하여 false
대기하고 대기 시간 초과가 만료될 때까지 차단합니다. 두 번째 스레드는 첫 번째 스레드가 종료된 후 실행되고 가 로 설정된 를 사용하여 exitContext
대기합니다. true
이 두 번째 스레드에 대한 대기 핸들을 신호로 알리는 호출은 차단되지 않으며 대기 시간 제한 전에 스레드가 완료됩니다.
using namespace System;
using namespace System::Threading;
using namespace System::Runtime::Remoting::Contexts;
[Synchronization(true)]
public ref class SyncingClass : ContextBoundObject
{
private:
EventWaitHandle^ waitHandle;
public:
SyncingClass()
{
waitHandle =
gcnew EventWaitHandle(false, EventResetMode::ManualReset);
}
void Signal()
{
Console::WriteLine("Thread[{0:d4}]: Signalling...", Thread::CurrentThread->GetHashCode());
waitHandle->Set();
}
void DoWait(bool leaveContext)
{
bool signalled;
waitHandle->Reset();
Console::WriteLine("Thread[{0:d4}]: Waiting...", Thread::CurrentThread->GetHashCode());
signalled = waitHandle->WaitOne(3000, leaveContext);
if (signalled)
{
Console::WriteLine("Thread[{0:d4}]: Wait released!!!", Thread::CurrentThread->GetHashCode());
}
else
{
Console::WriteLine("Thread[{0:d4}]: Wait timeout!!!", Thread::CurrentThread->GetHashCode());
}
}
};
public ref class TestSyncDomainWait
{
public:
static void Main()
{
SyncingClass^ syncClass = gcnew SyncingClass();
Thread^ runWaiter;
Console::WriteLine("\nWait and signal INSIDE synchronization domain:\n");
runWaiter = gcnew Thread(gcnew ParameterizedThreadStart(&TestSyncDomainWait::RunWaitKeepContext));
runWaiter->Start(syncClass);
Thread::Sleep(1000);
Console::WriteLine("Thread[{0:d4}]: Signal...", Thread::CurrentThread->GetHashCode());
// This call to Signal will block until the timeout in DoWait expires.
syncClass->Signal();
runWaiter->Join();
Console::WriteLine("\nWait and signal OUTSIDE synchronization domain:\n");
runWaiter = gcnew Thread(gcnew ParameterizedThreadStart(&TestSyncDomainWait::RunWaitLeaveContext));
runWaiter->Start(syncClass);
Thread::Sleep(1000);
Console::WriteLine("Thread[{0:d4}]: Signal...", Thread::CurrentThread->GetHashCode());
// This call to Signal is unblocked and will set the wait handle to
// release the waiting thread.
syncClass->Signal();
runWaiter->Join();
}
static void RunWaitKeepContext(Object^ parm)
{
((SyncingClass^)parm)->DoWait(false);
}
static void RunWaitLeaveContext(Object^ parm)
{
((SyncingClass^)parm)->DoWait(true);
}
};
int main()
{
TestSyncDomainWait::Main();
}
// The output for the example program will be similar to the following:
//
// Wait and signal INSIDE synchronization domain:
//
// Thread[0004]: Waiting...
// Thread[0001]: Signal...
// Thread[0004]: Wait timeout!!!
// Thread[0001]: Signalling...
//
// Wait and signal OUTSIDE synchronization domain:
//
// Thread[0006]: Waiting...
// Thread[0001]: Signal...
// Thread[0001]: Signalling...
// Thread[0006]: Wait released!!!
using System;
using System.Threading;
using System.Runtime.Remoting.Contexts;
[Synchronization(true)]
public class SyncingClass : ContextBoundObject
{
private EventWaitHandle waitHandle;
public SyncingClass()
{
waitHandle =
new EventWaitHandle(false, EventResetMode.ManualReset);
}
public void Signal()
{
Console.WriteLine("Thread[{0:d4}]: Signalling...", Thread.CurrentThread.GetHashCode());
waitHandle.Set();
}
public void DoWait(bool leaveContext)
{
bool signalled;
waitHandle.Reset();
Console.WriteLine("Thread[{0:d4}]: Waiting...", Thread.CurrentThread.GetHashCode());
signalled = waitHandle.WaitOne(3000, leaveContext);
if (signalled)
{
Console.WriteLine("Thread[{0:d4}]: Wait released!!!", Thread.CurrentThread.GetHashCode());
}
else
{
Console.WriteLine("Thread[{0:d4}]: Wait timeout!!!", Thread.CurrentThread.GetHashCode());
}
}
}
public class TestSyncDomainWait
{
public static void Main()
{
SyncingClass syncClass = new SyncingClass();
Thread runWaiter;
Console.WriteLine("\nWait and signal INSIDE synchronization domain:\n");
runWaiter = new Thread(RunWaitKeepContext);
runWaiter.Start(syncClass);
Thread.Sleep(1000);
Console.WriteLine("Thread[{0:d4}]: Signal...", Thread.CurrentThread.GetHashCode());
// This call to Signal will block until the timeout in DoWait expires.
syncClass.Signal();
runWaiter.Join();
Console.WriteLine("\nWait and signal OUTSIDE synchronization domain:\n");
runWaiter = new Thread(RunWaitLeaveContext);
runWaiter.Start(syncClass);
Thread.Sleep(1000);
Console.WriteLine("Thread[{0:d4}]: Signal...", Thread.CurrentThread.GetHashCode());
// This call to Signal is unblocked and will set the wait handle to
// release the waiting thread.
syncClass.Signal();
runWaiter.Join();
}
public static void RunWaitKeepContext(object parm)
{
((SyncingClass)parm).DoWait(false);
}
public static void RunWaitLeaveContext(object parm)
{
((SyncingClass)parm).DoWait(true);
}
}
// The output for the example program will be similar to the following:
//
// Wait and signal INSIDE synchronization domain:
//
// Thread[0004]: Waiting...
// Thread[0001]: Signal...
// Thread[0004]: Wait timeout!!!
// Thread[0001]: Signalling...
//
// Wait and signal OUTSIDE synchronization domain:
//
// Thread[0006]: Waiting...
// Thread[0001]: Signal...
// Thread[0001]: Signalling...
// Thread[0006]: Wait released!!!
Imports System.Threading
Imports System.Runtime.Remoting.Contexts
<Synchronization(true)>
Public Class SyncingClass
Inherits ContextBoundObject
Private waitHandle As EventWaitHandle
Public Sub New()
waitHandle = New EventWaitHandle(false, EventResetMode.ManualReset)
End Sub
Public Sub Signal()
Console.WriteLine("Thread[{0:d4}]: Signalling...", Thread.CurrentThread.GetHashCode())
waitHandle.Set()
End Sub
Public Sub DoWait(leaveContext As Boolean)
Dim signalled As Boolean
waitHandle.Reset()
Console.WriteLine("Thread[{0:d4}]: Waiting...", Thread.CurrentThread.GetHashCode())
signalled = waitHandle.WaitOne(3000, leaveContext)
If signalled Then
Console.WriteLine("Thread[{0:d4}]: Wait released!!!", Thread.CurrentThread.GetHashCode())
Else
Console.WriteLine("Thread[{0:d4}]: Wait timeout!!!", Thread.CurrentThread.GetHashCode())
End If
End Sub
End Class
Public Class TestSyncDomainWait
Public Shared Sub Main()
Dim syncClass As New SyncingClass()
Dim runWaiter As Thread
Console.WriteLine(Environment.NewLine + "Wait and signal INSIDE synchronization domain:" + Environment.NewLine)
runWaiter = New Thread(AddressOf RunWaitKeepContext)
runWaiter.Start(syncClass)
Thread.Sleep(1000)
Console.WriteLine("Thread[{0:d4}]: Signal...", Thread.CurrentThread.GetHashCode())
' This call to Signal will block until the timeout in DoWait expires.
syncClass.Signal()
runWaiter.Join()
Console.WriteLine(Environment.NewLine + "Wait and signal OUTSIDE synchronization domain:" + Environment.NewLine)
runWaiter = New Thread(AddressOf RunWaitLeaveContext)
runWaiter.Start(syncClass)
Thread.Sleep(1000)
Console.WriteLine("Thread[{0:d4}]: Signal...", Thread.CurrentThread.GetHashCode())
' This call to Signal is unblocked and will set the wait handle to
' release the waiting thread.
syncClass.Signal()
runWaiter.Join()
End Sub
Public Shared Sub RunWaitKeepContext(parm As Object)
Dim syncClass As SyncingClass = CType(parm, SyncingClass)
syncClass.DoWait(False)
End Sub
Public Shared Sub RunWaitLeaveContext(parm As Object)
Dim syncClass As SyncingClass = CType(parm, SyncingClass)
syncClass.DoWait(True)
End Sub
End Class
' The output for the example program will be similar to the following:
'
' Wait and signal INSIDE synchronization domain:
'
' Thread[0004]: Waiting...
' Thread[0001]: Signal...
' Thread[0004]: Wait timeout!!!
' Thread[0001]: Signalling...
'
' Wait and signal OUTSIDE synchronization domain:
'
' Thread[0006]: Waiting...
' Thread[0001]: Signal...
' Thread[0001]: Signalling...
' Thread[0006]: Wait released!!!
설명
millisecondsTimeout
가 0이면 메서드가 차단되지 않습니다. 대기 핸들의 상태를 테스트하고 즉시 반환합니다.
AbandonedMutexException는 .NET Framework 버전 2.0의 새로운 버전입니다. 이전 버전에서 WaitOne 메서드는 true
뮤텍스가 중단될 때 를 반환합니다. 중단된 뮤텍스는 종종 심각한 코딩 오류를 나타냅니다. 시스템 차원 뮤텍스의 경우 (예를 들어 Windows 작업 관리자 사용)가 애플리케이션이 갑자기 종료 된 나타낼 수 있습니다. 예외에는 디버깅에 유용한 정보가 포함되어 있습니다.
이 메서드의 호출자는 현재 인스턴스가 신호를 받거나 시간제한이 발생할 때까지 차단됩니다. 비동기 작업이 완료될 때 가 생성되는 등의 신호를 다른 스레드에서 받을 때까지 이 메서드를 사용하여 WaitHandle 차단합니다. 자세한 내용은 IAsyncResult 인터페이스를 참조하세요.
파생된 클래스의 동작을 사용자 지정 하려면이 메서드를 재정의 합니다.
컨텍스트 종료에 대한 참고 사항
exitContext
매개 변수는 WaitOne 메서드가 비기본 관리 컨텍스트 내에서 호출되지 않는 한 아무런 영향을 미치지 않습니다. 스레드가 에서 파생된 클래스의 인스턴스에 대한 호출 내에 있는 경우에 발생할 수 ContextBoundObject 있습니다. 파생 되지 않은 클래스에 메서드를 현재 실행 중인 경우에 ContextBoundObject같은 String, 기본이 아닌 컨텍스트에서 할 경우를 ContextBoundObject 가 현재 애플리케이션 도메인에서 스택에 합니다.
코드가 기본이 아닌 컨텍스트에서 실행되는 경우 true
에 을 exitContext
지정하면 메서드를 실행하기 전에 스레드가 기본이 아닌 관리되는 컨텍스트(즉, 기본 컨텍스트로 전환)를 WaitOne 종료합니다. 메서드 호출이 완료된 후 스레드가 원래의 비기본 컨텍스트로 WaitOne 돌아갑니다.
컨텍스트 바인딩된 클래스에 가 있는 경우에 유용할 수 SynchronizationAttribute 있습니다. 이 경우 클래스의 멤버에 대한 모든 호출이 자동으로 동기화되고 동기화 도메인은 클래스에 대한 코드의 전체 본문입니다. 멤버의 호출 스택에 있는 코드가 WaitOne 메서드를 호출하고 에 대해 를 지정하는 경우 true
exitContext
스레드는 동기화 도메인을 종료하여 개체의 모든 멤버에 대한 호출에서 차단된 스레드가 계속 진행되도록 합니다. WaitOne메서드가 반환되면 호출한 스레드가 동기화 도메인을 다시 활성화하기 위해 대기해야 합니다.
적용 대상
WaitOne(TimeSpan, Boolean)
TimeSpan로 시간 간격을 지정하고 대기 전에 동기화 도메인을 끝낼지 여부를 지정하여 현재 인스턴스가 신호를 받을 때까지 현재 스레드를 차단합니다.
public:
virtual bool WaitOne(TimeSpan timeout, bool exitContext);
public virtual bool WaitOne (TimeSpan timeout, bool exitContext);
abstract member WaitOne : TimeSpan * bool -> bool
override this.WaitOne : TimeSpan * bool -> bool
Public Overridable Function WaitOne (timeout As TimeSpan, exitContext As Boolean) As Boolean
매개 변수
- exitContext
- Boolean
대기 전에 컨텍스트에 대한 동기화 도메인을 종료하고(동기화된 컨텍스트에 있는 경우) 이 도메인을 다시 가져오려면 true
이고, 그렇지 않으면 false
입니다.
반환
현재 인스턴스가 신호를 받으면 true
이고, 그렇지 않으면 false
입니다.
예외
현재 인스턴스가 이미 삭제된 경우
timeout
은 시간 제한이 없음을 나타내는 -1밀리초 이외의 음수입니다.
또는
timeout
가 MaxValue보다 큰 경우
스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.
현재 인스턴스가 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시인 경우
예제
다음 코드 예제에서는 백그라운드 스레드의 실행이 완료되기를 기다리는 동안 프로세스가 종료되지 않도록 대기 핸들을 사용하는 방법을 보여줍니다.
using namespace System;
using namespace System::Threading;
ref class WaitOne
{
private:
WaitOne(){}
public:
static void WorkMethod( Object^ stateInfo )
{
Console::WriteLine( "Work starting." );
// Simulate time spent working.
Thread::Sleep( (gcnew Random)->Next( 100, 2000 ) );
// Signal that work is finished.
Console::WriteLine( "Work ending." );
dynamic_cast<AutoResetEvent^>(stateInfo)->Set();
}
};
int main()
{
Console::WriteLine( "Main starting." );
AutoResetEvent^ autoEvent = gcnew AutoResetEvent( false );
ThreadPool::QueueUserWorkItem( gcnew WaitCallback( &WaitOne::WorkMethod ), autoEvent );
// Wait for work method to signal.
if ( autoEvent->WaitOne( TimeSpan(0,0,1), false ) )
{
Console::WriteLine( "Work method signaled." );
}
else
{
Console::WriteLine( "Timed out waiting for work "
"method to signal." );
}
Console::WriteLine( "Main ending." );
}
using System;
using System.Threading;
class WaitOne
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main()
{
Console.WriteLine("Main starting.");
ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkMethod), autoEvent);
// Wait for work method to signal.
if(autoEvent.WaitOne(new TimeSpan(0, 0, 1), false))
{
Console.WriteLine("Work method signaled.");
}
else
{
Console.WriteLine("Timed out waiting for work " +
"method to signal.");
}
Console.WriteLine("Main ending.");
}
static void WorkMethod(object stateInfo)
{
Console.WriteLine("Work starting.");
// Simulate time spent working.
Thread.Sleep(new Random().Next(100, 2000));
// Signal that work is finished.
Console.WriteLine("Work ending.");
((AutoResetEvent)stateInfo).Set();
}
}
Imports System.Threading
Public Class WaitOne
Shared autoEvent As New AutoResetEvent(False)
<MTAThread> _
Shared Sub Main()
Console.WriteLine("Main starting.")
ThreadPool.QueueUserWorkItem(AddressOf WorkMethod, autoEvent)
' Wait for work method to signal.
If autoEvent.WaitOne(New TimeSpan(0, 0, 1), False) Then
Console.WriteLine("Work method signaled.")
Else
Console.WriteLine("Timed out waiting for work " & _
"method to signal.")
End If
Console.WriteLine("Main ending.")
End Sub
Shared Sub WorkMethod(stateInfo As Object)
Console.WriteLine("Work starting.")
' Simulate time spent working.
Thread.Sleep(New Random().Next(100, 2000))
' Signal that work is finished.
Console.WriteLine("Work ending.")
CType(stateInfo, AutoResetEvent).Set()
End Sub
End Class
설명
timeout
가 0이면 메서드가 차단되지 않습니다. 대기 핸들의 상태를 테스트하고 즉시 반환합니다.
AbandonedMutexException는 .NET Framework 버전 2.0의 새로운 버전입니다. 이전 버전에서 WaitOne 메서드는 true
뮤텍스가 중단될 때 를 반환합니다. 중단된 뮤텍스는 종종 심각한 코딩 오류를 나타냅니다. 시스템 차원 뮤텍스의 경우 (예를 들어 Windows 작업 관리자 사용)가 애플리케이션이 갑자기 종료 된 나타낼 수 있습니다. 예외에는 디버깅에 유용한 정보가 포함되어 있습니다.
이 메서드의 호출자는 현재 인스턴스가 신호를 받거나 시간제한이 발생할 때까지 차단됩니다. 비동기 작업이 완료될 때 가 생성되는 등의 신호를 다른 스레드에서 받을 때까지 이 메서드를 사용하여 WaitHandle 차단합니다. 자세한 내용은 IAsyncResult 인터페이스를 참조하세요.
파생된 클래스의 동작을 사용자 지정 하려면이 메서드를 재정의 합니다.
의 timeout
최대값은 Int32.MaxValue 입니다.
컨텍스트 종료에 대한 참고 사항
exitContext
매개 변수는 WaitOne 메서드가 비기본 관리 컨텍스트 내에서 호출되지 않는 한 아무런 영향을 미치지 않습니다. 스레드가 에서 파생된 클래스의 인스턴스에 대한 호출 내에 있는 경우에 발생할 수 ContextBoundObject 있습니다. 파생 되지 않은 클래스에 메서드를 현재 실행 중인 경우에 ContextBoundObject같은 String, 기본이 아닌 컨텍스트에서 할 경우를 ContextBoundObject 가 현재 애플리케이션 도메인에서 스택에 합니다.
코드가 기본이 아닌 컨텍스트에서 실행되는 경우 true
에 을 exitContext
지정하면 메서드를 실행하기 전에 스레드가 기본이 아닌 관리되는 컨텍스트(즉, 기본 컨텍스트로 전환)를 WaitOne 종료합니다. 메서드 호출이 완료된 후 스레드가 원래의 비기본 컨텍스트로 WaitOne 돌아갑니다.
컨텍스트 바인딩된 클래스에 가 있는 경우에 유용할 수 SynchronizationAttribute 있습니다. 이 경우 클래스의 멤버에 대한 모든 호출이 자동으로 동기화되고 동기화 도메인은 클래스에 대한 코드의 전체 본문입니다. 멤버의 호출 스택에 있는 코드가 WaitOne 메서드를 호출하고 에 대해 를 지정하는 경우 true
exitContext
스레드는 동기화 도메인을 종료하여 개체의 모든 멤버에 대한 호출에서 차단된 스레드가 계속 진행되도록 합니다. WaitOne메서드가 반환되면 호출한 스레드가 동기화 도메인을 다시 활성화하기 위해 대기해야 합니다.