WaitHandle.WaitAll 메서드

정의

지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

오버로드

WaitAll(WaitHandle[], TimeSpan, Boolean)

TimeSpan 값을 사용하여 시간 간격을 측정하고 대기 전에 동기화 도메인을 끝낼지 여부를 지정하여 지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

WaitAll(WaitHandle[], Int32, Boolean)

Int32 값을 사용하여 시간 간격을 지정하고 대기 전에 동기화 도메인을 끝낼지 여부를 지정하여 지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

WaitAll(WaitHandle[], TimeSpan)

TimeSpan 값을 사용하여 시간 간격을 지정함으로써 지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

WaitAll(WaitHandle[], Int32)

시간 간격을 지정하는 Int32 값을 사용하여 지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

WaitAll(WaitHandle[])

지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

WaitAll(WaitHandle[], TimeSpan, Boolean)

TimeSpan 값을 사용하여 시간 간격을 측정하고 대기 전에 동기화 도메인을 끝낼지 여부를 지정하여 지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

public:
 static bool WaitAll(cli::array <System::Threading::WaitHandle ^> ^ waitHandles, TimeSpan timeout, bool exitContext);
public static bool WaitAll (System.Threading.WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext);
static member WaitAll : System.Threading.WaitHandle[] * TimeSpan * bool -> bool
Public Shared Function WaitAll (waitHandles As WaitHandle(), timeout As TimeSpan, exitContext As Boolean) As Boolean

매개 변수

waitHandles
WaitHandle[]

현재 인스턴스에서 기다릴 개체가 포함된 WaitHandle 배열입니다. 이 배열에는 같은 개체에 대한 여러 개의 참조가 포함될 수 없습니다.

timeout
TimeSpan

대기할 시간(밀리초)을 나타내는 TimeSpan이거나, 무한 대기하도록 -1밀리초를 나타내는 TimeSpan입니다.

exitContext
Boolean

대기 전에 컨텍스트에 대한 동기화 도메인을 종료하고(동기화된 컨텍스트에 있는 경우) 이 도메인을 다시 가져오려면 true이고, 그렇지 않으면 false입니다.

반환

waitHandles에 있는 모든 요소가 신호를 받으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

예외

waitHandles 매개 변수가 null인 경우

또는

waitHandles 배열에 있는 하나 이상의 개체가 null인 경우

또는

waitHandles가 요소가 없는 배열이며 .NET Framework 버전이 2.0 이상인 경우

waitHandles 배열에 중복된 요소가 포함된 경우

waitHandles의 개체 수가 시스템에서 허용하는 것보다 큰 경우

또는

STAThreadAttribute 특성이 현재 스레드에 대한 스레드 프로시저에 적용되고 waitHandles에 둘 이상의 요소가 포함되어 있는 경우

waitHandles가 요소가 없는 배열이며 .NET Framework 버전이 1.0 또는 1.1인 경우

timeout 은 시간 제한이 없음을 나타내는 -1밀리초 이외의 음수입니다.

또는

timeoutInt32.MaxValue보다 큽 수 있습니다.

스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 종료되었습니다.

waitHandles 배열에 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시가 포함되어 있습니다.

예제

다음 코드 예제에서는 스레드 풀을 사용하여 파일 그룹을 비동기적으로 만들고 쓰는 방법을 보여줍니다. 각 쓰기 작업은 작업 항목으로 큐에 대기되고 완료되면 신호를 보냅니다. 기본 스레드는 모든 항목이 신호를 대기한 다음 종료됩니다.

using namespace System;
using namespace System::IO;
using namespace System::Security::Permissions;
using namespace System::Threading;

// Maintain state to pass to WriteToFile.
ref class State
{
public:
   String^ fileName;
   array<Byte>^byteArray;
   ManualResetEvent^ manualEvent;
   State( String^ fileName, array<Byte>^byteArray, ManualResetEvent^ manualEvent )
      : fileName( fileName ), byteArray( byteArray ), manualEvent( manualEvent )
   {}

};

ref class Writer
{
private:
   static int workItemCount = 0;
   Writer(){}


public:
   static void WriteToFile( Object^ state )
   {
      int workItemNumber = workItemCount;
      Interlocked::Increment( workItemCount );
      Console::WriteLine( "Starting work item {0}.", workItemNumber.ToString() );
      State^ stateInfo = dynamic_cast<State^>(state);
      FileStream^ fileWriter;
      
      // Create and write to the file.
      try
      {
         fileWriter = gcnew FileStream( stateInfo->fileName,FileMode::Create );
         fileWriter->Write( stateInfo->byteArray, 0, stateInfo->byteArray->Length );
      }
      finally
      {
         if ( fileWriter != nullptr )
         {
            fileWriter->Close();
         }
         
         // Signal main() that the work item has finished.
         Console::WriteLine( "Ending work item {0}.", workItemNumber.ToString() );
         stateInfo->manualEvent->Set();
      }

   }

};

int main()
{
   const int numberOfFiles = 5;
   String^ dirName =  "C:\\TestTest";
   String^ fileName;
   array<Byte>^byteArray;
   Random^ randomGenerator = gcnew Random;
   array<ManualResetEvent^>^manualEvents = gcnew array<ManualResetEvent^>(numberOfFiles);
   State^ stateInfo;
   if (  !Directory::Exists( dirName ) )
   {
      Directory::CreateDirectory( dirName );
   }

   
   // Queue the work items that create and write to the files.
   for ( int i = 0; i < numberOfFiles; i++ )
   {
      fileName = String::Concat( dirName,  "\\Test", ((i)).ToString(),  ".dat" );
      
      // Create random data to write to the file.
      byteArray = gcnew array<Byte>(1000000);
      randomGenerator->NextBytes( byteArray );
      manualEvents[ i ] = gcnew ManualResetEvent( false );
      stateInfo = gcnew State( fileName,byteArray,manualEvents[ i ] );
      ThreadPool::QueueUserWorkItem( gcnew WaitCallback( &Writer::WriteToFile ), stateInfo );

   }
   
   // Since ThreadPool threads are background threads, 
   // wait for the work items to signal before exiting.
   if ( WaitHandle::WaitAll( manualEvents, TimeSpan(0,0,5), false ) )
   {
      Console::WriteLine( "Files written - main exiting." );
   }
   else
   {
      
      // The wait operation times out.
      Console::WriteLine( "Error writing files - main exiting." );
   }
}
using System;
using System.IO;
using System.Security.Permissions;
using System.Threading;

class Test
{
    static void Main()
    {
        const int numberOfFiles = 5;
        string dirName = @"C:\TestTest";
        string fileName;

        byte[] byteArray;
        Random randomGenerator = new Random();

        ManualResetEvent[] manualEvents = 
            new ManualResetEvent[numberOfFiles];
        State stateInfo;

        if(!Directory.Exists(dirName))
        {
            Directory.CreateDirectory(dirName);
        }

        // Queue the work items that create and write to the files.
        for(int i = 0; i < numberOfFiles; i++)
        {
            fileName = string.Concat(
                dirName, @"\Test", i.ToString(), ".dat");

            // Create random data to write to the file.
            byteArray = new byte[1000000];
            randomGenerator.NextBytes(byteArray);

            manualEvents[i] = new ManualResetEvent(false);

            stateInfo = 
                new State(fileName, byteArray, manualEvents[i]);

            ThreadPool.QueueUserWorkItem(new WaitCallback(
                Writer.WriteToFile), stateInfo);
        }
    
        // Since ThreadPool threads are background threads, 
        // wait for the work items to signal before exiting.
        if(WaitHandle.WaitAll(
            manualEvents, new TimeSpan(0, 0, 5), false))
        {
            Console.WriteLine("Files written - main exiting.");
        }
        else
        {
            // The wait operation times out.
            Console.WriteLine("Error writing files - main exiting.");
        }
    }
}

// Maintain state to pass to WriteToFile.
class State
{
    public string fileName;
    public byte[] byteArray;
    public ManualResetEvent manualEvent;

    public State(string fileName, byte[] byteArray, 
        ManualResetEvent manualEvent)
    {
        this.fileName = fileName;
        this.byteArray = byteArray;
        this.manualEvent = manualEvent;
    }
}

class Writer
{
    static int workItemCount = 0;
    Writer() {}

    public static void WriteToFile(object state)
    {
        int workItemNumber = workItemCount;
        Interlocked.Increment(ref workItemCount);
        Console.WriteLine("Starting work item {0}.",
            workItemNumber.ToString());
        State stateInfo = (State)state;
        FileStream fileWriter = null;

        // Create and write to the file.
        try
        {
            fileWriter = new FileStream(
                stateInfo.fileName, FileMode.Create);
            fileWriter.Write(stateInfo.byteArray, 
                0, stateInfo.byteArray.Length);
        }
        finally
        {
            if(fileWriter != null)
            {
                fileWriter.Close();
            }

            // Signal Main that the work item has finished.
            Console.WriteLine("Ending work item {0}.", 
                workItemNumber.ToString());
            stateInfo.manualEvent.Set();
        }
    }
}
Imports System.IO
Imports System.Security.Permissions
Imports System.Threading

Public Class Test

    ' WaitHandle.WaitAll requires a multithreaded apartment 
    ' when using multiple wait handles.
    <MTAThreadAttribute> _
    Shared Sub Main()
        Const numberOfFiles As Integer = 5
        Dim dirName As String = "C:\TestTest"
        Dim fileName As String 

        Dim byteArray() As Byte 
        Dim randomGenerator As New Random()

        Dim manualEvents(numberOfFiles - 1) As ManualResetEvent
        Dim stateInfo As State 

        If Directory.Exists(dirName) <> True Then
            Directory.CreateDirectory(dirName)
        End If

        ' Queue the work items that create and write to the files.
        For i As Integer = 0 To numberOfFiles - 1
            fileName = String.Concat( _
                dirName, "\Test", i.ToString(), ".dat")

            ' Create random data to write to the file.
            byteArray = New Byte(1000000){}
            randomGenerator.NextBytes(byteArray)

            manualEvents(i) = New ManualResetEvent(false)

            stateInfo = _ 
                New State(fileName, byteArray, manualEvents(i))

            ThreadPool.QueueUserWorkItem(AddressOf _
                Writer.WriteToFile, stateInfo)
        Next i
    
        ' Since ThreadPool threads are background threads, 
        ' wait for the work items to signal before exiting.
        If WaitHandle.WaitAll( _
            manualEvents, New TimeSpan(0, 0, 5), false) = True  Then

            Console.WriteLine("Files written - main exiting.")
        Else
        
            ' The wait operation times out.
            Console.WriteLine("Error writing files - main exiting.")
        End If
    End Sub

End Class
 
' Maintain state to pass to WriteToFile.
Public Class State

    Public fileName As String
    Public byteArray As Byte()
    Public manualEvent As ManualResetEvent

    Sub New(fileName As String, byteArray() As Byte, _
        manualEvent As ManualResetEvent)
    
        Me.fileName = fileName
        Me.byteArray = byteArray
        Me.manualEvent = manualEvent
    End Sub

End Class

Public Class Writer

    Private Sub New()
    End Sub

    Shared workItemCount As Integer = 0

    Shared Sub WriteToFile(state As Object)
        Dim workItemNumber As Integer = workItemCount
        Interlocked.Increment(workItemCount)
        Console.WriteLine("Starting work item {0}.", _
            workItemNumber.ToString())
        Dim stateInfo As State = CType(state, State)
        Dim fileWriter As FileStream = Nothing

        ' Create and write to the file.
        Try
            fileWriter = New FileStream( _
                stateInfo.fileName, FileMode.Create)
            fileWriter.Write(stateInfo.byteArray, _
                0, stateInfo.byteArray.Length)
        Finally
            If Not fileWriter Is Nothing Then
                fileWriter.Close()
            End If

            ' Signal Main that the work item has finished.
            Console.WriteLine("Ending work item {0}.", _
                workItemNumber.ToString())
            stateInfo.manualEvent.Set()
        End Try
    End Sub

End Class

설명

가 0이면 timeout 메서드가 차단되지 않습니다. 대기 핸들의 상태를 테스트하고 즉시 반환합니다.

뮤텍스가 중단되면 이 AbandonedMutexException throw됩니다. 중단된 뮤텍스는 심각한 코딩 오류를 나타내는 경우가 많습니다. 시스템 차원 뮤텍스의 경우 (예를 들어 Windows 작업 관리자 사용)가 애플리케이션이 갑자기 종료 된 나타낼 수 있습니다. 예외에는 디버깅에 유용한 정보가 포함되어 있습니다.

메서드는 WaitAll 대기가 종료될 때 를 반환합니다. 즉, 모든 핸들이 신호를 받거나 시간 초과가 발생합니다. 64개 이상의 핸들이 전달되면 이 NotSupportedException throw됩니다. 배열에 중복 항목이 포함되어 있으면 호출이 실패합니다.

참고

메서드는 WaitAll 상태의 스레드에서 STA 지원되지 않습니다.

timeout 최대값은 입니다 Int32.MaxValue.

컨텍스트 종료

exitContext 메서드가 기본이 아닌 관리되는 컨텍스트 내에서 호출되지 않는 한 매개 변수는 영향을 주지 않습니다. 스레드가 에서 ContextBoundObject파생된 클래스의 instance 대한 호출 내에 있는 경우 관리되는 컨텍스트는 기본이 아닐 수 있습니다. 와 같이 String에서 파생되지 않은 클래스에서 ContextBoundObject메서드를 현재 실행 중인 경우에도 가 현재 애플리케이션 도메인의 스택에 있는 경우 ContextBoundObject 기본이 아닌 컨텍스트에 있을 수 있습니다.

코드가 기본이 아닌 컨텍스트에서 실행되는 경우 을 지정하면 trueexitContext 이 메서드를 실행하기 전에 스레드가 기본 컨텍스트로 전환하기 위해 기본이 아닌 관리되는 컨텍스트(즉, 기본 컨텍스트로 전환)를 종료합니다. 스레드는 이 메서드에 대한 호출이 완료된 후 원래의 기본이 아닌 컨텍스트로 돌아갑니다.

컨텍스트를 종료하는 것은 컨텍스트 바인딩된 클래스에 특성이 SynchronizationAttribute 있는 경우에 유용할 수 있습니다. 이 경우 클래스의 멤버에 대한 모든 호출이 자동으로 동기화되고 동기화 도메인은 클래스의 전체 코드 본문입니다. 멤버의 호출 스택에 있는 코드가 이 메서드를 호출하고 에 를 exitContext지정 true 하는 경우 스레드는 동기화 도메인을 종료합니다. 그러면 개체의 멤버를 호출할 때 차단된 스레드를 계속 진행할 수 있습니다. 이 메서드가 반환되면 호출한 스레드가 동기화 도메인을 다시 입력하기 위해 대기해야 합니다.

적용 대상

WaitAll(WaitHandle[], Int32, Boolean)

Int32 값을 사용하여 시간 간격을 지정하고 대기 전에 동기화 도메인을 끝낼지 여부를 지정하여 지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

public:
 static bool WaitAll(cli::array <System::Threading::WaitHandle ^> ^ waitHandles, int millisecondsTimeout, bool exitContext);
public static bool WaitAll (System.Threading.WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext);
static member WaitAll : System.Threading.WaitHandle[] * int * bool -> bool
Public Shared Function WaitAll (waitHandles As WaitHandle(), millisecondsTimeout As Integer, exitContext As Boolean) As Boolean

매개 변수

waitHandles
WaitHandle[]

현재 인스턴스에서 기다릴 개체가 포함된 WaitHandle 배열입니다. 이 배열에는 같은 개체(중복 개체)에 대한 여러 개의 참조가 포함될 수 없습니다.

millisecondsTimeout
Int32

대기할 시간(밀리초)이거나, 무기한 대기할 경우 Infinite(-1)입니다.

exitContext
Boolean

대기 전에 컨텍스트에 대한 동기화 도메인을 종료하고(동기화된 컨텍스트에 있는 경우) 이 도메인을 다시 가져오려면 true이고, 그렇지 않으면 false입니다.

반환

waitHandles에 있는 모든 요소가 신호를 받으면 true이고, 그렇지 않으면 false입니다.

예외

waitHandles 매개 변수가 null인 경우

또는

waitHandles 배열에 있는 하나 이상의 개체가 null인 경우

또는

waitHandles가 요소가 없는 배열이며 .NET Framework 버전이 2.0 이상인 경우

waitHandles 배열에 중복된 요소가 포함된 경우

waitHandles의 개체 수가 시스템에서 허용하는 것보다 큰 경우

또는

현재 스레드가 STA 상태이고 waitHandles에 요소가 두 개 이상 포함되어 있습니다.

waitHandles가 요소가 없는 배열이며 .NET Framework 버전이 1.0 또는 1.1인 경우

millisecondsTimeout이 시간 제한 없음을 나타내는 -1 이외의 음수인 경우

스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.

waitHandles 배열에 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시가 포함되어 있습니다.

예제

다음 코드 예제에서는 스레드 풀을 사용하여 파일 그룹을 비동기적으로 만들고 쓰는 방법을 보여줍니다. 각 쓰기 작업은 작업 항목으로 큐에 대기되고 완료되면 신호를 보냅니다. 기본 스레드는 모든 항목이 신호를 대기한 다음 종료됩니다.

using namespace System;
using namespace System::IO;
using namespace System::Security::Permissions;
using namespace System::Threading;

// Maintain state to pass to WriteToFile.
ref class State
{
public:
   String^ fileName;
   array<Byte>^byteArray;
   ManualResetEvent^ manualEvent;
   State( String^ fileName, array<Byte>^byteArray, ManualResetEvent^ manualEvent )
      : fileName( fileName ), byteArray( byteArray ), manualEvent( manualEvent )
   {}

};

ref class Writer
{
private:
   static int workItemCount = 0;
   Writer(){}


public:
   static void WriteToFile( Object^ state )
   {
      int workItemNumber = workItemCount;
      Interlocked::Increment( workItemCount );
      Console::WriteLine( "Starting work item {0}.", workItemNumber.ToString() );
      State^ stateInfo = dynamic_cast<State^>(state);
      FileStream^ fileWriter;
      
      // Create and write to the file.
      try
      {
         fileWriter = gcnew FileStream( stateInfo->fileName,FileMode::Create );
         fileWriter->Write( stateInfo->byteArray, 0, stateInfo->byteArray->Length );
      }
      finally
      {
         if ( fileWriter != nullptr )
         {
            fileWriter->Close();
         }
         
         // Signal main() that the work item has finished.
         Console::WriteLine( "Ending work item {0}.", workItemNumber.ToString() );
         stateInfo->manualEvent->Set();
      }

   }

};

int main()
{
   const int numberOfFiles = 5;
   String^ dirName =  "C:\\TestTest";
   String^ fileName;
   array<Byte>^byteArray;
   Random^ randomGenerator = gcnew Random;
   array<ManualResetEvent^>^manualEvents = gcnew array<ManualResetEvent^>(numberOfFiles);
   State^ stateInfo;
   if (  !Directory::Exists( dirName ) )
   {
      Directory::CreateDirectory( dirName );
   }

   
   // Queue the work items that create and write to the files.
   for ( int i = 0; i < numberOfFiles; i++ )
   {
      fileName = String::Concat( dirName,  "\\Test", ((i)).ToString(),  ".dat" );
      
      // Create random data to write to the file.
      byteArray = gcnew array<Byte>(1000000);
      randomGenerator->NextBytes( byteArray );
      manualEvents[ i ] = gcnew ManualResetEvent( false );
      stateInfo = gcnew State( fileName,byteArray,manualEvents[ i ] );
      ThreadPool::QueueUserWorkItem( gcnew WaitCallback( &Writer::WriteToFile ), stateInfo );

   }
   
   // Since ThreadPool threads are background threads, 
   // wait for the work items to signal before exiting.
   if ( WaitHandle::WaitAll( manualEvents, 5000, false ) )
   {
      Console::WriteLine( "Files written - main exiting." );
   }
   else
   {
      
      // The wait operation times out.
      Console::WriteLine( "Error writing files - main exiting." );
   }
}
using System;
using System.IO;
using System.Security.Permissions;
using System.Threading;

class Test
{
    static void Main()
    {
        const int numberOfFiles = 5;
        string dirName = @"C:\TestTest";
        string fileName;

        byte[] byteArray;
        Random randomGenerator = new Random();

        ManualResetEvent[] manualEvents = 
            new ManualResetEvent[numberOfFiles];
        State stateInfo;

        if(!Directory.Exists(dirName))
        {
            Directory.CreateDirectory(dirName);
        }

        // Queue the work items that create and write to the files.
        for(int i = 0; i < numberOfFiles; i++)
        {
            fileName = string.Concat(
                dirName, @"\Test", i.ToString(), ".dat");

            // Create random data to write to the file.
            byteArray = new byte[1000000];
            randomGenerator.NextBytes(byteArray);

            manualEvents[i] = new ManualResetEvent(false);

            stateInfo = 
                new State(fileName, byteArray, manualEvents[i]);

            ThreadPool.QueueUserWorkItem(new WaitCallback(
                Writer.WriteToFile), stateInfo);
        }
    
        // Since ThreadPool threads are background threads, 
        // wait for the work items to signal before exiting.
        if(WaitHandle.WaitAll(manualEvents, 5000, false))
        {
            Console.WriteLine("Files written - main exiting.");
        }
        else
        {
            // The wait operation times out.
            Console.WriteLine("Error writing files - main exiting.");
        }
    }
}

// Maintain state to pass to WriteToFile.
class State
{
    public string fileName;
    public byte[] byteArray;
    public ManualResetEvent manualEvent;

    public State(string fileName, byte[] byteArray, 
        ManualResetEvent manualEvent)
    {
        this.fileName = fileName;
        this.byteArray = byteArray;
        this.manualEvent = manualEvent;
    }
}

class Writer
{
    static int workItemCount = 0;
    Writer() {}

    public static void WriteToFile(object state)
    {
        int workItemNumber = workItemCount;
        Interlocked.Increment(ref workItemCount);
        Console.WriteLine("Starting work item {0}.",
            workItemNumber.ToString());
        State stateInfo = (State)state;
        FileStream fileWriter = null;

        // Create and write to the file.
        try
        {
            fileWriter = new FileStream(
                stateInfo.fileName, FileMode.Create);
            fileWriter.Write(stateInfo.byteArray, 
                0, stateInfo.byteArray.Length);
        }
        finally
        {
            if(fileWriter != null)
            {
                fileWriter.Close();
            }

            // Signal Main that the work item has finished.
            Console.WriteLine("Ending work item {0}.", 
                workItemNumber.ToString());
            stateInfo.manualEvent.Set();
        }
    }
}
Imports System.IO
Imports System.Security.Permissions
Imports System.Threading

Public Class Test

    ' WaitHandle.WaitAll requires a multithreaded apartment 
    ' when using multiple wait handles.
    <MTAThreadAttribute> _
    Shared Sub Main()
        Const numberOfFiles As Integer = 5
        Dim dirName As String = "C:\TestTest"
        Dim fileName As String 

        Dim byteArray() As Byte 
        Dim randomGenerator As New Random()

        Dim manualEvents(numberOfFiles - 1) As ManualResetEvent
        Dim stateInfo As State 

        If Directory.Exists(dirName) <> True Then
            Directory.CreateDirectory(dirName)
        End If

        ' Queue the work items that create and write to the files.
        For i As Integer = 0 To numberOfFiles - 1
            fileName = String.Concat( _
                dirName, "\Test", i.ToString(), ".dat")

            ' Create random data to write to the file.
            byteArray = New Byte(1000000){}
            randomGenerator.NextBytes(byteArray)

            manualEvents(i) = New ManualResetEvent(false)

            stateInfo = _ 
                New State(fileName, byteArray, manualEvents(i))

            ThreadPool.QueueUserWorkItem(AddressOf _
                Writer.WriteToFile, stateInfo)
        Next i
    
        ' Since ThreadPool threads are background threads, 
        ' wait for the work items to signal before exiting.
        If WaitHandle.WaitAll(manualEvents, 5000, false) = True  Then

            Console.WriteLine("Files written - main exiting.")
        Else
        
            ' The wait operation times out.
            Console.WriteLine("Error writing files - main exiting.")
        End If
    End Sub

End Class
 
' Maintain state to pass to WriteToFile.
Public Class State

    Public fileName As String
    Public byteArray As Byte()
    Public manualEvent As ManualResetEvent

    Sub New(fileName As String, byteArray() As Byte, _
        manualEvent As ManualResetEvent)
    
        Me.fileName = fileName
        Me.byteArray = byteArray
        Me.manualEvent = manualEvent
    End Sub

End Class

Public Class Writer

    Private Sub New()
    End Sub

    Shared workItemCount As Integer = 0

    Shared Sub WriteToFile(state As Object)
        Dim workItemNumber As Integer = workItemCount
        Interlocked.Increment(workItemCount)
        Console.WriteLine("Starting work item {0}.", _
            workItemNumber.ToString())
        Dim stateInfo As State = CType(state, State)
        Dim fileWriter As FileStream = Nothing

        ' Create and write to the file.
        Try
            fileWriter = New FileStream( _
                stateInfo.fileName, FileMode.Create)
            fileWriter.Write(stateInfo.byteArray, _
                0, stateInfo.byteArray.Length)
        Finally
            If Not fileWriter Is Nothing Then
                fileWriter.Close()
            End If

            ' Signal Main that the work item has finished.
            Console.WriteLine("Ending work item {0}.", _
                workItemNumber.ToString())
            stateInfo.manualEvent.Set()
        End Try
    End Sub

End Class

설명

가 0이면 millisecondsTimeout 메서드가 차단되지 않습니다. 대기 핸들의 상태를 테스트하고 즉시 반환합니다.

뮤텍스가 중단되면 이 AbandonedMutexException throw됩니다. 중단된 뮤텍스는 심각한 코딩 오류를 나타내는 경우가 많습니다. 시스템 차원 뮤텍스의 경우 (예를 들어 Windows 작업 관리자 사용)가 애플리케이션이 갑자기 종료 된 나타낼 수 있습니다. 예외에는 디버깅에 유용한 정보가 포함되어 있습니다.

메서드는 WaitAll 대기가 종료될 때 를 반환합니다. 즉, 모든 핸들이 신호를 받거나 시간 초과가 발생할 때를 의미합니다. 64개 이상의 핸들이 전달되면 이 NotSupportedException throw됩니다. 배열에 중복이 있는 경우 와 함께 호출이 DuplicateWaitObjectException실패합니다.

참고

메서드는 WaitAll 상태의 스레드에서 STA 지원되지 않습니다.

컨텍스트 종료

exitContext 메서드가 기본이 아닌 관리되는 컨텍스트 내에서 호출되지 않는 한 매개 변수는 영향을 주지 않습니다. 스레드가 에서 ContextBoundObject파생된 클래스의 instance 대한 호출 내에 있는 경우 관리되는 컨텍스트는 기본이 아닐 수 있습니다. 와 같이 String에서 파생되지 않은 클래스에서 ContextBoundObject메서드를 현재 실행 중인 경우에도 가 현재 애플리케이션 도메인의 스택에 있는 경우 ContextBoundObject 기본이 아닌 컨텍스트에 있을 수 있습니다.

코드가 기본이 아닌 컨텍스트에서 실행되는 경우 을 지정하면 trueexitContext 이 메서드를 실행하기 전에 스레드가 기본 컨텍스트로 전환하기 위해 기본이 아닌 관리되는 컨텍스트(즉, 기본 컨텍스트로 전환)를 종료합니다. 스레드는 이 메서드에 대한 호출이 완료된 후 원래의 기본이 아닌 컨텍스트로 돌아갑니다.

컨텍스트를 종료하는 것은 컨텍스트 바인딩된 클래스에 특성이 SynchronizationAttribute 있는 경우에 유용할 수 있습니다. 이 경우 클래스의 멤버에 대한 모든 호출이 자동으로 동기화되고 동기화 도메인은 클래스의 전체 코드 본문입니다. 멤버의 호출 스택에 있는 코드가 이 메서드를 호출하고 에 를 exitContext지정 true 하는 경우 스레드는 동기화 도메인을 종료합니다. 그러면 개체의 멤버를 호출할 때 차단된 스레드를 계속 진행할 수 있습니다. 이 메서드가 반환되면 호출한 스레드가 동기화 도메인을 다시 입력하기 위해 대기해야 합니다.

적용 대상

WaitAll(WaitHandle[], TimeSpan)

TimeSpan 값을 사용하여 시간 간격을 지정함으로써 지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

public:
 static bool WaitAll(cli::array <System::Threading::WaitHandle ^> ^ waitHandles, TimeSpan timeout);
public static bool WaitAll (System.Threading.WaitHandle[] waitHandles, TimeSpan timeout);
static member WaitAll : System.Threading.WaitHandle[] * TimeSpan -> bool
Public Shared Function WaitAll (waitHandles As WaitHandle(), timeout As TimeSpan) As Boolean

매개 변수

waitHandles
WaitHandle[]

현재 인스턴스에서 기다릴 개체가 포함된 WaitHandle 배열입니다. 이 배열에는 같은 개체에 대한 여러 개의 참조가 포함될 수 없습니다.

timeout
TimeSpan

대기할 시간(밀리초)을 나타내는 TimeSpan이거나, 무한 대기하도록 -1밀리초를 나타내는 TimeSpan입니다.

반환

waitHandles에 있는 모든 요소가 신호를 받으면 true이고, 그렇지 않으면 false입니다.

예외

waitHandles 매개 변수가 null인 경우

또는

waitHandles 배열에 있는 하나 이상의 개체가 null인 경우

또는

waitHandles가 요소가 없는 배열인 경우

waitHandles 배열에 중복된 요소가 포함된 경우

참고: Windows 스토어 앱용 .NET 또는 이식 가능한 클래스 라이브러리에서 대신 기본 클래스 예외 ArgumentException을 catch합니다.

waitHandles의 개체 수가 시스템에서 허용하는 것보다 큰 경우

또는

현재 스레드가 STA 상태이고 waitHandles에 요소가 두 개 이상 포함되어 있습니다.

timeout 은 시간 제한이 없음을 나타내는 -1밀리초 이외의 음수입니다.

또는

timeoutInt32.MaxValue보다 큽 수 있습니다.

스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 종료되었습니다.

waitHandles 배열에 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시가 포함되어 있습니다.

설명

가 0이면 timeout 메서드가 차단되지 않습니다. 대기 핸들의 상태를 테스트하고 즉시 반환합니다.

메서드는 WaitAll 대기가 종료될 때 를 반환합니다. 즉, 모든 핸들이 신호를 받거나 시간 초과가 발생합니다. 64개 이상의 핸들이 전달되면 이 NotSupportedException throw됩니다. 배열에 중복 항목이 포함되어 있으면 호출이 실패합니다.

참고

메서드는 WaitAll 상태의 스레드에서 STA 지원되지 않습니다.

timeout 최대값은 입니다 Int32.MaxValue.

이 메서드 오버로드를 호출하는 것은 오버로드를 WaitAll(WaitHandle[], TimeSpan, Boolean) 호출하고 에 를 exitContext지정하는 false 것과 동일합니다.

적용 대상

WaitAll(WaitHandle[], Int32)

시간 간격을 지정하는 Int32 값을 사용하여 지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

public:
 static bool WaitAll(cli::array <System::Threading::WaitHandle ^> ^ waitHandles, int millisecondsTimeout);
public static bool WaitAll (System.Threading.WaitHandle[] waitHandles, int millisecondsTimeout);
static member WaitAll : System.Threading.WaitHandle[] * int -> bool
Public Shared Function WaitAll (waitHandles As WaitHandle(), millisecondsTimeout As Integer) As Boolean

매개 변수

waitHandles
WaitHandle[]

현재 인스턴스에서 기다릴 개체가 포함된 WaitHandle 배열입니다. 이 배열에는 같은 개체(중복 개체)에 대한 여러 개의 참조가 포함될 수 없습니다.

millisecondsTimeout
Int32

대기할 시간(밀리초)이거나, 무기한 대기할 경우 Infinite(-1)입니다.

반환

waitHandles에 있는 모든 요소가 신호를 받으면 true이고, 그렇지 않으면 false입니다.

예외

waitHandles 매개 변수가 null인 경우

또는

waitHandles 배열에 있는 하나 이상의 개체가 null인 경우

또는

waitHandles가 요소가 없는 배열인 경우

waitHandles 배열에 중복된 요소가 포함된 경우

참고: Windows 스토어 앱용 .NET 또는 이식 가능한 클래스 라이브러리에서 대신 기본 클래스 예외 ArgumentException을 catch합니다.

waitHandles의 개체 수가 시스템에서 허용하는 것보다 큰 경우

또는

현재 스레드가 STA 상태이고 waitHandles에 요소가 두 개 이상 포함되어 있습니다.

millisecondsTimeout이 시간 제한 없음을 나타내는 -1 이외의 음수인 경우

스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.

waitHandles 배열에 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시가 포함되어 있습니다.

설명

가 0이면 millisecondsTimeout 메서드가 차단되지 않습니다. 대기 핸들의 상태를 테스트하고 즉시 반환합니다.

메서드는 WaitAll 대기가 종료될 때 를 반환합니다. 즉, 모든 핸들이 신호를 받거나 시간 초과가 발생할 때를 의미합니다. 64개 이상의 핸들이 전달되면 이 NotSupportedException throw됩니다. 배열에 중복이 있는 경우 와 함께 호출이 DuplicateWaitObjectException실패합니다.

참고

메서드는 WaitAll 상태의 스레드에서 STA 지원되지 않습니다.

이 메서드 오버로드를 호출하는 것은 오버로드를 WaitAll(WaitHandle[], Int32, Boolean) 호출하고 에 를 exitContext지정하는 false 것과 동일합니다.

적용 대상

WaitAll(WaitHandle[])

지정된 배열의 모든 요소가 신호를 받기를 기다립니다.

public:
 static bool WaitAll(cli::array <System::Threading::WaitHandle ^> ^ waitHandles);
public static bool WaitAll (System.Threading.WaitHandle[] waitHandles);
static member WaitAll : System.Threading.WaitHandle[] -> bool
Public Shared Function WaitAll (waitHandles As WaitHandle()) As Boolean

매개 변수

waitHandles
WaitHandle[]

현재 인스턴스에서 기다릴 개체가 포함된 WaitHandle 배열입니다. 이 배열에는 같은 개체에 대한 여러 개의 참조가 포함될 수 없습니다.

반환

waitHandles의 모든 요소가 신호를 받으면 true를 반환하고, 그렇지 않으면 아무 값도 반환하지 않습니다.

예외

waitHandles 매개 변수가 null인 경우 또는

null 배열에 있는 하나 이상의 개체가 waitHandles인 경우

또는

waitHandles가 요소가 없는 배열이며 .NET Framework 버전이 2.0 이상인 경우

waitHandles 배열에 중복된 요소가 포함된 경우

참고: Windows 스토어 앱용 .NET 또는 이식 가능한 클래스 라이브러리에서 대신 기본 클래스 예외 ArgumentException을 catch합니다.

waitHandles의 개체 수가 시스템에서 허용하는 것보다 큰 경우

또는

현재 스레드가 STA 상태이고 waitHandles에 요소가 두 개 이상 포함되어 있습니다.

waitHandles가 요소가 없는 배열이며 .NET Framework 버전이 1.0 또는 1.1인 경우

스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 종료되었습니다.

waitHandles 배열에 다른 애플리케이션 도메인에 있는 WaitHandle에 대한 투명 프록시가 포함되어 있습니다.

예제

다음 코드 예제에서는 스레드 풀을 사용하여 파일 그룹을 비동기적으로 만들고 쓰는 방법을 보여줍니다. 각 쓰기 작업은 작업 항목으로 큐에 대기되고 완료되면 신호를 보냅니다. 기본 스레드는 모든 항목이 신호를 대기한 다음 종료됩니다.

using namespace System;
using namespace System::IO;
using namespace System::Security::Permissions;
using namespace System::Threading;

ref class State
{
public:
   String^ fileName;
   array<Byte>^byteArray;
   ManualResetEvent^ manualEvent;
   State( String^ fileName, array<Byte>^byteArray, ManualResetEvent^ manualEvent )
      : fileName( fileName ), byteArray( byteArray ), manualEvent( manualEvent )
   {}

};

ref class Writer
{
private:
   static int workItemCount = 0;
   Writer(){}


public:
   static void WriteToFile( Object^ state )
   {
      int workItemNumber = workItemCount;
      Interlocked::Increment( workItemCount );
      Console::WriteLine( "Starting work item {0}.", workItemNumber.ToString() );
      State^ stateInfo = dynamic_cast<State^>(state);
      FileStream^ fileWriter;
      
      // Create and write to the file.
      try
      {
         fileWriter = gcnew FileStream( stateInfo->fileName,FileMode::Create );
         fileWriter->Write( stateInfo->byteArray, 0, stateInfo->byteArray->Length );
      }
      finally
      {
         if ( fileWriter != nullptr )
         {
            fileWriter->Close();
         }
         
         // Signal main() that the work item has finished.
         Console::WriteLine( "Ending work item {0}.", workItemNumber.ToString() );
         stateInfo->manualEvent->Set();
      }

   }

};

void main()
{
   const int numberOfFiles = 5;
   String^ dirName =  "C:\\TestTest";
   String^ fileName;
   array<Byte>^byteArray;
   Random^ randomGenerator = gcnew Random;
   array<ManualResetEvent^>^manualEvents = gcnew array<ManualResetEvent^>(numberOfFiles);
   State^ stateInfo;
   if (  !Directory::Exists( dirName ) )
   {
      Directory::CreateDirectory( dirName );
   }

   
   // Queue the work items that create and write to the files.
   for ( int i = 0; i < numberOfFiles; i++ )
   {
      fileName = String::Concat( dirName,  "\\Test", ((i)).ToString(),  ".dat" );
      
      // Create random data to write to the file.
      byteArray = gcnew array<Byte>(1000000);
      randomGenerator->NextBytes( byteArray );
      manualEvents[ i ] = gcnew ManualResetEvent( false );
      stateInfo = gcnew State( fileName,byteArray,manualEvents[ i ] );
      ThreadPool::QueueUserWorkItem( gcnew WaitCallback( &Writer::WriteToFile ), stateInfo );

   }
   
   // Since ThreadPool threads are background threads, 
   // wait for the work items to signal before exiting.
   WaitHandle::WaitAll( manualEvents );
   Console::WriteLine( "Files written - main exiting." );
}
using System;
using System.IO;
using System.Security.Permissions;
using System.Threading;

class Test
{
    static void Main()
    {
        const int numberOfFiles = 5;
        string dirName = @"C:\TestTest";
        string fileName;

        byte[] byteArray;
        Random randomGenerator = new Random();

        ManualResetEvent[] manualEvents = 
            new ManualResetEvent[numberOfFiles];
        State stateInfo;

        if(!Directory.Exists(dirName))
        {
            Directory.CreateDirectory(dirName);
        }

        // Queue the work items that create and write to the files.
        for(int i = 0; i < numberOfFiles; i++)
        {
            fileName = string.Concat(
                dirName, @"\Test", i.ToString(), ".dat");

            // Create random data to write to the file.
            byteArray = new byte[1000000];
            randomGenerator.NextBytes(byteArray);

            manualEvents[i] = new ManualResetEvent(false);

            stateInfo = 
                new State(fileName, byteArray, manualEvents[i]);

            ThreadPool.QueueUserWorkItem(new WaitCallback(
                Writer.WriteToFile), stateInfo);
        }
    
        // Since ThreadPool threads are background threads, 
        // wait for the work items to signal before exiting.
        WaitHandle.WaitAll(manualEvents);
        Console.WriteLine("Files written - main exiting.");
    }
}

// Maintain state to pass to WriteToFile.
class State
{
    public string fileName;
    public byte[] byteArray;
    public ManualResetEvent manualEvent;

    public State(string fileName, byte[] byteArray, 
        ManualResetEvent manualEvent)
    {
        this.fileName = fileName;
        this.byteArray = byteArray;
        this.manualEvent = manualEvent;
    }
}

class Writer
{
    static int workItemCount = 0;
    Writer() {}

    public static void WriteToFile(object state)
    {
        int workItemNumber = workItemCount;
        Interlocked.Increment(ref workItemCount);
        Console.WriteLine("Starting work item {0}.",
            workItemNumber.ToString());
        State stateInfo = (State)state;
        FileStream fileWriter = null;

        // Create and write to the file.
        try
        {
            fileWriter = new FileStream(
                stateInfo.fileName, FileMode.Create);
            fileWriter.Write(stateInfo.byteArray, 
                0, stateInfo.byteArray.Length);
        }
        finally
        {
            if(fileWriter != null)
            {
                fileWriter.Close();
            }

            // Signal Main that the work item has finished.
            Console.WriteLine("Ending work item {0}.", 
                workItemNumber.ToString());
            stateInfo.manualEvent.Set();
        }
    }
}
Imports System.IO
Imports System.Security.Permissions
Imports System.Threading

Public Class Test

    ' WaitHandle.WaitAll requires a multithreaded apartment 
    ' when using multiple wait handles.
    <MTAThreadAttribute> _
    Shared Sub Main()
        Const numberOfFiles As Integer = 5
        Dim dirName As String = "C:\TestTest"
        Dim fileName As String 

        Dim byteArray() As Byte 
        Dim randomGenerator As New Random()

        Dim manualEvents(numberOfFiles - 1) As ManualResetEvent
        Dim stateInfo As State 

        If Directory.Exists(dirName) <> True Then
            Directory.CreateDirectory(dirName)
        End If

        ' Queue the work items that create and write to the files.
        For i As Integer = 0 To numberOfFiles - 1
            fileName = String.Concat( _
                dirName, "\Test", i.ToString(), ".dat")

            ' Create random data to write to the file.
            byteArray = New Byte(1000000){}
            randomGenerator.NextBytes(byteArray)

            manualEvents(i) = New ManualResetEvent(false)

            stateInfo = _ 
                New State(fileName, byteArray, manualEvents(i))

            ThreadPool.QueueUserWorkItem(AddressOf _
                Writer.WriteToFile, stateInfo)
        Next i
    
        ' Since ThreadPool threads are background threads, 
        ' wait for the work items to signal before exiting.
        WaitHandle.WaitAll(manualEvents)
        Console.WriteLine("Files written - main exiting.")
    End Sub

End Class
 
' Maintain state to pass to WriteToFile.
Public Class State

    Public fileName As String
    Public byteArray As Byte()
    Public manualEvent As ManualResetEvent

    Sub New(fileName As String, byteArray() As Byte, _
        manualEvent As ManualResetEvent)
    
        Me.fileName = fileName
        Me.byteArray = byteArray
        Me.manualEvent = manualEvent
    End Sub

End Class

Public Class Writer

    Private Sub New()
    End Sub

    Shared workItemCount As Integer = 0

    Shared Sub WriteToFile(state As Object)
        Dim workItemNumber As Integer = workItemCount
        Interlocked.Increment(workItemCount)
        Console.WriteLine("Starting work item {0}.", _
            workItemNumber.ToString())
        Dim stateInfo As State = CType(state, State)
        Dim fileWriter As FileStream = Nothing

        ' Create and write to the file.
        Try
            fileWriter = New FileStream( _
                stateInfo.fileName, FileMode.Create)
            fileWriter.Write(stateInfo.byteArray, _
                0, stateInfo.byteArray.Length)
        Finally
            If Not fileWriter Is Nothing Then
                fileWriter.Close()
            End If

            ' Signal Main that the work item has finished.
            Console.WriteLine("Ending work item {0}.", _
                workItemNumber.ToString())
            stateInfo.manualEvent.Set()
        End Try
    End Sub

End Class

설명

AbandonedMutexException는 .NET Framework 버전 2.0의 새로운 기능입니다. 이전 버전에서 메서드는 WaitAll 뮤텍스가 중단되면 를 반환 true 합니다. 중단된 뮤텍스는 심각한 코딩 오류를 나타내는 경우가 많습니다. 시스템 차원 뮤텍스의 경우 (예를 들어 Windows 작업 관리자 사용)가 애플리케이션이 갑자기 종료 된 나타낼 수 있습니다. 예외에는 디버깅에 유용한 정보가 포함되어 있습니다.

메서드는 WaitAll 모든 핸들이 신호를 받으면 를 반환합니다. 64개 이상의 핸들이 전달되면 이 NotSupportedException throw됩니다. 배열에 중복 항목이 포함되어 있으면 와 함께 호출이 DuplicateWaitObjectException실패합니다.

참고

메서드는 WaitAll 상태의 스레드에서 STA 지원되지 않습니다.

이 메서드 오버로드를 호출하는 것은 메서드 오버로드를 WaitAll(WaitHandle[], Int32, Boolean) 호출하고 및 에 대해 -1(또는 Timeout.Infinite)을 millisecondsTimeouttrueexitContext지정하는 것과 같습니다.

적용 대상