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 配列内の 1 つ以上のオブジェクトが 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 がスローされます。 破棄されたミューテックスは、多くの場合、深刻なコーディング エラーを示します。 システム全体のミューテックスの場合、アプリケーションが突然終了したことを示している可能性があります (たとえば、Windows タスク マネージャーを使用)。 例外には、デバッグに役立つ情報が含まれています。

メソッドは WaitAll 、待機が終了すると を返します。つまり、すべてのハンドルがシグナル通知されるか、タイムアウトが発生します。 64 個を超えるハンドルが渡されると、 NotSupportedException がスローされます。 配列に重複が含まれている場合、呼び出しは失敗します。

注意

メソッドは WaitAll 、状態のスレッドでは STA サポートされていません。

timeout 最大値は です Int32.MaxValue

コンテキストの終了

パラメーターは、既定以外の exitContext マネージド コンテキスト内からこのメソッドが呼び出されない限り、効果はありません。 スレッドが から ContextBoundObject派生したクラスのインスタンスの呼び出し内にある場合、マネージド コンテキストは既定以外の状態にすることができます。 など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 配列内の 1 つ以上のオブジェクトが 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 がスローされます。 破棄されたミューテックスは、多くの場合、深刻なコーディング エラーを示します。 システム全体のミューテックスの場合、アプリケーションが突然終了したことを示している可能性があります (たとえば、Windows タスク マネージャーを使用)。 例外には、デバッグに役立つ情報が含まれています。

メソッドは WaitAll 、待機が終了すると を返します。つまり、すべてのハンドルがシグナル通知されたとき、またはタイムアウトが発生した場合です。 64 個を超えるハンドルが渡されると、 NotSupportedException がスローされます。 配列に重複がある場合、呼び出しは で失敗します DuplicateWaitObjectException

注意

メソッドは WaitAll 、状態のスレッドでは STA サポートされていません。

コンテキストの終了

パラメーターは、既定以外の exitContext マネージド コンテキスト内からこのメソッドが呼び出されない限り、効果はありません。 スレッドが から ContextBoundObject派生したクラスのインスタンスの呼び出し内にある場合、マネージド コンテキストは既定以外の状態にすることができます。 など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 配列内の 1 つ以上のオブジェクトが null です。

- または -

waitHandles は、要素を持たない配列です。

waitHandles 配列に、重複する要素が含まれています。

注意: Windows ストア アプリ用 .NET またはポータブル クラス ライブラリでは、基本クラスの例外である ArgumentException を代わりにキャッチします。

waitHandles のオブジェクトの数が、システムで許可されている範囲を超えています。

- または -

現在のスレッドの状態が STA であり、waitHandles に複数の要素が含まれています。

timeout は無限のタイムアウトを表す -1 ミリ秒以外の負の数です。

または

timeoutInt32.MaxValue より大きい。

スレッドがミューテックスを解放せずに終了したため、待機が終了しました。

waitHandles 配列には、別のアプリケーション ドメインのWaitHandle の透過プロキシが含まれます。

注釈

が 0 の場合 timeout 、メソッドはブロックしません。 待機ハンドルの状態をテストし、すぐにを返します。

メソッドは WaitAll 、待機が終了すると を返します。つまり、すべてのハンドルがシグナル通知されるか、タイムアウトが発生します。 64 個を超えるハンドルが渡されると、 NotSupportedException がスローされます。 配列に重複が含まれている場合、呼び出しは失敗します。

注意

メソッドは 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 配列内の 1 つ以上のオブジェクトが null です。

- または -

waitHandles は、要素を持たない配列です。

waitHandles 配列に、重複する要素が含まれています。

注意: Windows ストア アプリ用 .NET またはポータブル クラス ライブラリでは、基本クラスの例外である ArgumentException を代わりにキャッチします。

waitHandles のオブジェクトの数が、システムで許可されている範囲を超えています。

- または -

現在のスレッドの状態が STA であり、waitHandles に複数の要素が含まれています。

millisecondsTimeout は無限のタイムアウトを表す -1 以外の負の数です。

スレッドがミューテックスを解放せずに終了したため、待機が完了しました。

waitHandles 配列には、別のアプリケーション ドメインのWaitHandle の透過プロキシが含まれます。

注釈

が 0 の場合 millisecondsTimeout 、メソッドはブロックしません。 待機ハンドルの状態をテストし、すぐにを返します。

メソッドは WaitAll 、待機が終了すると を返します。つまり、すべてのハンドルがシグナル通知されたとき、またはタイムアウトが発生した場合です。 64 個を超えるハンドルが渡されると、 NotSupportedException がスローされます。 配列に重複がある場合、呼び出しは で失敗します 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 です。 - または -

waitHandles 配列内の 1 つ以上のオブジェクトが null です。

- または -

waitHandles は要素を持たない配列で、.NET Framework のバージョンが 2.0 以降です。

waitHandles 配列に、重複する要素が含まれています。

注意: Windows ストア アプリ用 .NET またはポータブル クラス ライブラリでは、基本クラスの例外である ArgumentException を代わりにキャッチします。

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 がスローされます。 配列に重複が含まれている場合、呼び出しは で DuplicateWaitObjectException失敗します。

注意

メソッドは WaitAll 、状態のスレッドでは STA サポートされていません。

このメソッド オーバーロードの呼び出しは、 メソッド オーバーロードを WaitAll(WaitHandle[], Int32, Boolean) 呼び出し、 および に対して -1 (または Timeout.Infinite) を millisecondsTimeouttrueexitContext指定することと同じです。

適用対象