WaitHandle.WaitAny 方法

定義

等候指定陣列中有任何項目收到信號。

多載

WaitAny(WaitHandle[])

等候指定陣列中有任何項目收到信號。

WaitAny(WaitHandle[], Int32)

等候指定之陣列中有任何項目收到信號,使用 32 位元帶正負號的整數以指定時間間隔。

WaitAny(WaitHandle[], TimeSpan)

等候指定陣列中的所有項目都收到信號,使用 TimeSpan 來指定時間間隔。

WaitAny(WaitHandle[], Int32, Boolean)

等候指定陣列中有任何項目收到信號;使用 32 位元帶正負號的整數 (Signed Integer) 來指定時間間隔,並指定是否在等候之前先離開同步處理領域。

WaitAny(WaitHandle[], TimeSpan, Boolean)

等候指定陣列中的所有項目都收到信號,使用 TimeSpan 來指定時間間隔,並指定是否要先離開同步處理網域,再開始等候。

WaitAny(WaitHandle[])

Source:
WaitHandle.cs
Source:
WaitHandle.cs
Source:
WaitHandle.cs

等候指定陣列中有任何項目收到信號。

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

參數

waitHandles
WaitHandle[]

WaitHandle 陣列,包含目前執行個體將等候的物件。

傳回

滿足等候條件之物件的陣列索引。

例外狀況

waitHandles 參數為 null

-或-

waitHandles 陣列中的一或多個物件為 null

waitHandles 中的物件數目超過系統允許的數目。

waitHandles 是不具有項目的陣列,且 .NET Framework 版本為 1.0 或 1.1。

由於執行緒結束時未釋放 Mutex,已完成等候。

waitHandles 是不具有元素的陣列,且 .NET Framework 版本為 2.0 (含) 以後版本。

waitHandles 陣列在另一個應用程式定義域中包含 WaitHandle 的 Transparent Proxy。

範例

下列程式代碼範例示範如何呼叫 WaitAny 方法。

using namespace System;
using namespace System::Threading;

public ref class WaitHandleExample
{
    // Define a random number generator for testing.
private:
    static Random^ random = gcnew Random();
public:
    static void DoTask(Object^ state)
    {
        AutoResetEvent^ autoReset = (AutoResetEvent^) state;
        int time = 1000 * random->Next(2, 10);
        Console::WriteLine("Performing a task for {0} milliseconds.", time);
        Thread::Sleep(time);
        autoReset->Set();
    }
};

int main()
{
    // Define an array with two AutoResetEvent WaitHandles.
    array<WaitHandle^>^ handles = gcnew array<WaitHandle^> {
        gcnew AutoResetEvent(false), gcnew AutoResetEvent(false)};

    // Queue up two tasks on two different threads;
    // wait until all tasks are completed.
    DateTime timeInstance = DateTime::Now;
    Console::WriteLine("Main thread is waiting for BOTH tasks to " +
        "complete.");
    ThreadPool::QueueUserWorkItem(
        gcnew WaitCallback(WaitHandleExample::DoTask), handles[0]);
    ThreadPool::QueueUserWorkItem(
        gcnew WaitCallback(WaitHandleExample::DoTask), handles[1]);
    WaitHandle::WaitAll(handles);
    // The time shown below should match the longest task.
    Console::WriteLine("Both tasks are completed (time waited={0})",
        (DateTime::Now - timeInstance).TotalMilliseconds);

    // Queue up two tasks on two different threads;
    // wait until any tasks are completed.
    timeInstance = DateTime::Now;
    Console::WriteLine();
    Console::WriteLine("The main thread is waiting for either task to " +
        "complete.");
    ThreadPool::QueueUserWorkItem(
        gcnew WaitCallback(WaitHandleExample::DoTask), handles[0]);
    ThreadPool::QueueUserWorkItem(
        gcnew WaitCallback(WaitHandleExample::DoTask), handles[1]);
    int index = WaitHandle::WaitAny(handles);
    // The time shown below should match the shortest task.
    Console::WriteLine("Task {0} finished first (time waited={1}).",
        index + 1, (DateTime::Now - timeInstance).TotalMilliseconds);
}

// This code produces the following sample output.
//
// Main thread is waiting for BOTH tasks to complete.
// Performing a task for 7000 milliseconds.
// Performing a task for 4000 milliseconds.
// Both tasks are completed (time waited=7064.8052)

// The main thread is waiting for either task to complete.
// Performing a task for 2000 milliseconds.
// Performing a task for 2000 milliseconds.
// Task 1 finished first (time waited=2000.6528).
using System;
using System.Threading;

public sealed class App
{
    // Define an array with two AutoResetEvent WaitHandles.
    static WaitHandle[] waitHandles = new WaitHandle[]
    {
        new AutoResetEvent(false),
        new AutoResetEvent(false)
    };

    // Define a random number generator for testing.
    static Random r = new Random();

    static void Main()
    {
        // Queue up two tasks on two different threads;
        // wait until all tasks are completed.
        DateTime dt = DateTime.Now;
        Console.WriteLine("Main thread is waiting for BOTH tasks to complete.");
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]);
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]);
        WaitHandle.WaitAll(waitHandles);
        // The time shown below should match the longest task.
        Console.WriteLine("Both tasks are completed (time waited={0})",
            (DateTime.Now - dt).TotalMilliseconds);

        // Queue up two tasks on two different threads;
        // wait until any task is completed.
        dt = DateTime.Now;
        Console.WriteLine();
        Console.WriteLine("The main thread is waiting for either task to complete.");
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]);
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]);
        int index = WaitHandle.WaitAny(waitHandles);
        // The time shown below should match the shortest task.
        Console.WriteLine("Task {0} finished first (time waited={1}).",
            index + 1, (DateTime.Now - dt).TotalMilliseconds);
    }

    static void DoTask(Object state)
    {
        AutoResetEvent are = (AutoResetEvent) state;
        int time = 1000 * r.Next(2, 10);
        Console.WriteLine("Performing a task for {0} milliseconds.", time);
        Thread.Sleep(time);
        are.Set();
    }
}

// This code produces output similar to the following:
//
//  Main thread is waiting for BOTH tasks to complete.
//  Performing a task for 7000 milliseconds.
//  Performing a task for 4000 milliseconds.
//  Both tasks are completed (time waited=7064.8052)
//
//  The main thread is waiting for either task to complete.
//  Performing a task for 2000 milliseconds.
//  Performing a task for 2000 milliseconds.
//  Task 1 finished first (time waited=2000.6528).
Imports System.Threading

NotInheritable Public Class App
    ' Define an array with two AutoResetEvent WaitHandles.
    Private Shared waitHandles() As WaitHandle = _
        {New AutoResetEvent(False), New AutoResetEvent(False)}
    
    ' Define a random number generator for testing.
    Private Shared r As New Random()
    
    <MTAThreadAttribute> _
    Public Shared Sub Main() 
        ' Queue two tasks on two different threads; 
        ' wait until all tasks are completed.
        Dim dt As DateTime = DateTime.Now
        Console.WriteLine("Main thread is waiting for BOTH tasks to complete.")
        ThreadPool.QueueUserWorkItem(AddressOf DoTask, waitHandles(0))
        ThreadPool.QueueUserWorkItem(AddressOf DoTask, waitHandles(1))
        WaitHandle.WaitAll(waitHandles)
        ' The time shown below should match the longest task.
        Console.WriteLine("Both tasks are completed (time waited={0})", _
            (DateTime.Now - dt).TotalMilliseconds)
        
        ' Queue up two tasks on two different threads; 
        ' wait until any tasks are completed.
        dt = DateTime.Now
        Console.WriteLine()
        Console.WriteLine("The main thread is waiting for either task to complete.")
        ThreadPool.QueueUserWorkItem(AddressOf DoTask, waitHandles(0))
        ThreadPool.QueueUserWorkItem(AddressOf DoTask, waitHandles(1))
        Dim index As Integer = WaitHandle.WaitAny(waitHandles)
        ' The time shown below should match the shortest task.
        Console.WriteLine("Task {0} finished first (time waited={1}).", _
            index + 1,(DateTime.Now - dt).TotalMilliseconds)
    
    End Sub
    
    Shared Sub DoTask(ByVal state As [Object]) 
        Dim are As AutoResetEvent = CType(state, AutoResetEvent)
        Dim time As Integer = 1000 * r.Next(2, 10)
        Console.WriteLine("Performing a task for {0} milliseconds.", time)
        Thread.Sleep(time)
        are.Set()
    
    End Sub
End Class

' This code produces output similar to the following:
'
'  Main thread is waiting for BOTH tasks to complete.
'  Performing a task for 7000 milliseconds.
'  Performing a task for 4000 milliseconds.
'  Both tasks are completed (time waited=7064.8052)
' 
'  The main thread is waiting for either task to complete.
'  Performing a task for 2000 milliseconds.
'  Performing a task for 2000 milliseconds.
'  Task 1 finished first (time waited=2000.6528).

備註

AbandonedMutexException是 .NET Framework 2.0 版的新功能。 在舊版中,如果等候完成,因為已放棄 mutex,此方法 WaitAny 會傳回 true 。 已放棄的 Mutex 通常表示嚴重的程式代碼撰寫錯誤。 在全系統 Mutex 的情況下,它可能表示應用程式已突然終止 (例如,使用 Windows 任務管理員) 。 例外狀況包含適用於偵錯的資訊。

只有在因為放棄的 mutex 而等候完成時,方法 WaitAny 才會擲 AbandonedMutexException 回 。 如果 waitHandles 包含索引編號低於已放棄 Mutex 的已釋放 Mutex,則 WaitAny 方法會正常完成,而且不會擲回例外狀況。

注意

在 2.0 版之前的 .NET Framework 版本中,如果線程結束或中止而不明確釋放 Mutex,且位於Mutex陣列中WaitAny索引 0 (零) ,則 傳WaitAny回的索引是 128 而不是 0。

當收到任何句柄的訊號時,這個方法會傳回 。 如果在呼叫期間收到多個物件的訊號,傳回值會是訊號對象的陣列索引,且所有訊號物件的索引值最小。

等候句柄的最大數目為 64,如果目前線程處於 STA 狀態,則為 63。

呼叫這個方法多載相當於呼叫 WaitAny(WaitHandle[], Int32, Boolean) 方法多載,併為 和 指定 -1 (或 Timeout.Infinite) millisecondsTimeouttrueexitContext

適用於

WaitAny(WaitHandle[], Int32)

Source:
WaitHandle.cs
Source:
WaitHandle.cs
Source:
WaitHandle.cs

等候指定之陣列中有任何項目收到信號,使用 32 位元帶正負號的整數以指定時間間隔。

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

參數

waitHandles
WaitHandle[]

WaitHandle 陣列,包含目前執行個體將等候的物件。

millisecondsTimeout
Int32

要等候的毫秒數,如果要無限期等候,則為 Infinite (-1)。

傳回

滿足等候條件之物件的陣列索引;如果沒有物件滿足等候條件,而且已經過相當於 millisecondsTimeout 的時間間隔,則為 WaitTimeout

例外狀況

waitHandles 參數為 null

-或-

waitHandles 陣列中的一或多個物件為 null

waitHandles 中的物件數目超過系統允許的數目。

millisecondsTimeout 為 -1 以外的負數,表示無限逾時。

由於執行緒結束時未釋放 Mutex,已完成等候。

waitHandles 是不含任何項目的陣列。

waitHandles 陣列在另一個應用程式定義域中包含 WaitHandle 的 Transparent Proxy。

備註

如果 millisecondsTimeout 為零,則方法不會封鎖。 它會測試等候句柄的狀態,並立即傳回。

只有在因為放棄的 mutex 而等候完成時,方法 WaitAny 才會擲 AbandonedMutexException 回 。 如果 waitHandles 包含索引編號低於已放棄 Mutex 的已釋放 Mutex,則 WaitAny 方法會正常完成,而且不會擲回例外狀況。

這個方法會在等候終止時傳回,可能是當收到任何句柄的訊號或發生逾時時。 如果在呼叫期間收到多個物件的訊號,傳回值會是訊號對象的陣列索引,且所有訊號物件的索引值最小。

等候句柄的最大數目為 64,如果目前線程處於 STA 狀態,則為 63。

呼叫這個方法多載與呼叫 WaitAny(WaitHandle[], Int32, Boolean) 多載和針對 exitContext指定false相同。

適用於

WaitAny(WaitHandle[], TimeSpan)

Source:
WaitHandle.cs
Source:
WaitHandle.cs
Source:
WaitHandle.cs

等候指定陣列中的所有項目都收到信號,使用 TimeSpan 來指定時間間隔。

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

參數

waitHandles
WaitHandle[]

WaitHandle 陣列,包含目前執行個體將等候的物件。

timeout
TimeSpan

TimeSpan,代表等候毫秒數;或是 TimeSpan,代表無限期等候的 -1 毫秒。

傳回

滿足等候條件之物件的陣列索引;如果沒有物件滿足等候條件,而且已經過相當於 timeout 的時間間隔,則為 WaitTimeout

例外狀況

waitHandles 參數為 null

-或-

waitHandles 陣列中的一或多個物件為 null

waitHandles 中的物件數目超過系統允許的數目。

timeout 為 -1 毫秒以外的負數,表示無限逾時。

-或-

timeout 大於 Int32.MaxValue

由於執行緒結束時未釋放 Mutex,已完成等候。

waitHandles 是不含任何項目的陣列。

waitHandles 陣列在另一個應用程式定義域中包含 WaitHandle 的 Transparent Proxy。

備註

如果 timeout 為零,則方法不會封鎖。 它會測試等候句柄的狀態,並立即傳回。

只有在因為放棄的 mutex 而等候完成時,方法 WaitAny 才會擲 AbandonedMutexException 回 。 如果 waitHandles 包含索引編號低於已放棄 Mutex 的已釋放 Mutex,則 WaitAny 方法會正常完成,而且不會擲回例外狀況。

當等候終止時,這個方法會傳回當收到任何句柄的訊號或發生逾時時。 如果在呼叫期間收到多個物件的訊號,傳回值會是訊號對象的陣列索引,且所有訊號物件的索引值最小。

等候句柄的最大數目為 64,如果目前線程處於 STA 狀態,則為 63。

最大 timeout 值為 Int32.MaxValue

呼叫這個方法多載與呼叫 WaitAny(WaitHandle[], TimeSpan, Boolean) 多載和針對 exitContext指定false相同。

適用於

WaitAny(WaitHandle[], Int32, Boolean)

Source:
WaitHandle.cs
Source:
WaitHandle.cs
Source:
WaitHandle.cs

等候指定陣列中有任何項目收到信號;使用 32 位元帶正負號的整數 (Signed Integer) 來指定時間間隔,並指定是否在等候之前先離開同步處理領域。

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

參數

waitHandles
WaitHandle[]

WaitHandle 陣列,包含目前執行個體將等候的物件。

millisecondsTimeout
Int32

要等候的毫秒數,如果要無限期等候,則為 Infinite (-1)。

exitContext
Boolean

true 表示在等候 (如果在同步內容中) 前結束內容的同步處理網域,並於之後重新取得,否則為 false

傳回

滿足等候條件之物件的陣列索引;如果沒有物件滿足等候條件,而且已經過相當於 millisecondsTimeout 的時間間隔,則為 WaitTimeout

例外狀況

waitHandles 參數為 null

-或-

waitHandles 陣列中的一或多個物件為 null

waitHandles 中的物件數目超過系統允許的數目。

waitHandles 是不具有項目的陣列,且 .NET Framework 版本為 1.0 或 1.1。

millisecondsTimeout 為 -1 以外的負數,表示無限逾時。

由於執行緒結束時未釋放 Mutex,已完成等候。

waitHandles 是不具有元素的陣列,且 .NET Framework 版本為 2.0 (含) 以後版本。

waitHandles 陣列在另一個應用程式定義域中包含 WaitHandle 的 Transparent Proxy。

範例

下列程式代碼範例示範如何使用線程集區同時搜尋多個磁碟上的檔案。 如需空間考慮,只會搜尋每個磁碟的根目錄。

using namespace System;
using namespace System::IO;
using namespace System::Threading;
ref class Search
{
private:

   // Maintain state information to pass to FindCallback.
   ref class State
   {
   public:
      AutoResetEvent^ autoEvent;
      String^ fileName;
      State( AutoResetEvent^ autoEvent, String^ fileName )
         : autoEvent( autoEvent ), fileName( fileName )
      {}

   };


public:
   array<AutoResetEvent^>^autoEvents;
   array<String^>^diskLetters;

   // Search for stateInfo->fileName.
   void FindCallback( Object^ state )
   {
      State^ stateInfo = dynamic_cast<State^>(state);
      
      // Signal if the file is found.
      if ( File::Exists( stateInfo->fileName ) )
      {
         stateInfo->autoEvent->Set();
      }
   }

   Search()
   {
      
      // Retrieve an array of disk letters.
      diskLetters = Environment::GetLogicalDrives();
      autoEvents = gcnew array<AutoResetEvent^>(diskLetters->Length);
      for ( int i = 0; i < diskLetters->Length; i++ )
      {
         autoEvents[ i ] = gcnew AutoResetEvent( false );

      }
   }


   // Search for fileName in the root directory of all disks.
   void FindFile( String^ fileName )
   {
      for ( int i = 0; i < diskLetters->Length; i++ )
      {
         Console::WriteLine(  "Searching for {0} on {1}.", fileName, diskLetters[ i ] );
         ThreadPool::QueueUserWorkItem( gcnew WaitCallback( this, &Search::FindCallback ), gcnew State( autoEvents[ i ],String::Concat( diskLetters[ i ], fileName ) ) );

      }
      
      // Wait for the first instance of the file to be found.
      int index = WaitHandle::WaitAny( autoEvents, 3000, false );
      if ( index == WaitHandle::WaitTimeout )
      {
         Console::WriteLine( "\n{0} not found.", fileName );
      }
      else
      {
         Console::WriteLine( "\n{0} found on {1}.", fileName, diskLetters[ index ] );
      }
   }

};

int main()
{
   Search^ search = gcnew Search;
   search->FindFile( "SomeFile.dat" );
}
using System;
using System.IO;
using System.Threading;

class Test
{
    static void Main()
    {
        Search search = new Search();
        search.FindFile("SomeFile.dat");
    }
}

class Search
{
    // Maintain state information to pass to FindCallback.
    class State
    {
        public AutoResetEvent autoEvent;
        public string         fileName;

        public State(AutoResetEvent autoEvent, string fileName)
        {
            this.autoEvent    = autoEvent;
            this.fileName     = fileName;
        }
    }

    AutoResetEvent[] autoEvents;
    String[] diskLetters;

    public Search()
    {
        // Retrieve an array of disk letters.
        diskLetters = Environment.GetLogicalDrives();

        autoEvents = new AutoResetEvent[diskLetters.Length];
        for(int i = 0; i < diskLetters.Length; i++)
        {
            autoEvents[i] = new AutoResetEvent(false);
        }
    }

    // Search for fileName in the root directory of all disks.
    public void FindFile(string fileName)
    {
        for(int i = 0; i < diskLetters.Length; i++)
        {
            Console.WriteLine("Searching for {0} on {1}.",
                fileName, diskLetters[i]);
            ThreadPool.QueueUserWorkItem(
                new WaitCallback(FindCallback), 
                new State(autoEvents[i], diskLetters[i] + fileName));
        }

        // Wait for the first instance of the file to be found.
        int index = WaitHandle.WaitAny(autoEvents, 3000, false);
        if(index == WaitHandle.WaitTimeout)
        {
            Console.WriteLine("\n{0} not found.", fileName);
        }
        else
        {
            Console.WriteLine("\n{0} found on {1}.", fileName,
                diskLetters[index]);
        }
    }

    // Search for stateInfo.fileName.
    void FindCallback(object state)
    {
        State stateInfo = (State)state;

        // Signal if the file is found.
        if(File.Exists(stateInfo.fileName))
        {
            stateInfo.autoEvent.Set();
        }
    }
}
Imports System.IO
Imports System.Threading

Public Class Test

    <MTAThread> _
    Shared Sub Main()
        Dim search As New Search()
        search.FindFile("SomeFile.dat")
    End Sub    
End Class

Public Class Search

    ' Maintain state information to pass to FindCallback.
    Class State
        Public autoEvent As AutoResetEvent 
        Public fileName As String         

        Sub New(anEvent As AutoResetEvent, fName As String)
            autoEvent = anEvent
            fileName = fName
        End Sub
    End Class

    Dim autoEvents() As AutoResetEvent
    Dim diskLetters() As String

    Sub New()

        ' Retrieve an array of disk letters.
        diskLetters = Environment.GetLogicalDrives()

        autoEvents = New AutoResetEvent(diskLetters.Length - 1) {}
        For i As Integer = 0 To diskLetters.Length - 1
            autoEvents(i) = New AutoResetEvent(False)
        Next i
    End Sub    
    
    ' Search for fileName in the root directory of all disks.
    Sub FindFile(fileName As String)
        For i As Integer = 0 To diskLetters.Length - 1
            Console.WriteLine("Searching for {0} on {1}.", _
                fileName, diskLetters(i))
        
            ThreadPool.QueueUserWorkItem(AddressOf FindCallback, _ 
                New State(autoEvents(i), diskLetters(i) & fileName))
        Next i

        ' Wait for the first instance of the file to be found.
        Dim index As Integer = _
            WaitHandle.WaitAny(autoEvents, 3000, False)
        If index = WaitHandle.WaitTimeout
            Console.WriteLine(vbCrLf & "{0} not found.", fileName)
        Else
            Console.WriteLine(vbCrLf & "{0} found on {1}.", _
                fileName, diskLetters(index))
        End If
    End Sub

    ' Search for stateInfo.fileName.
    Sub FindCallback(state As Object)
        Dim stateInfo As State = DirectCast(state, State)

        ' Signal if the file is found.
        If File.Exists(stateInfo.fileName) Then
            stateInfo.autoEvent.Set()
        End If
    End Sub

End Class

備註

如果 millisecondsTimeout 為零,則方法不會封鎖。 它會測試等候句柄的狀態,並立即傳回。

只有在因為放棄的 mutex 而等候完成時,方法 WaitAny 才會擲 AbandonedMutexException 回 。 如果 waitHandles 包含索引編號低於已放棄 Mutex 的已釋放 Mutex,則 WaitAny 方法會正常完成,而且不會擲回例外狀況。 已放棄的 Mutex 通常表示嚴重的程式代碼撰寫錯誤。 在全系統 Mutex 的情況下,它可能表示應用程式已突然終止 (例如,使用 Windows 任務管理員) 。 例外狀況包含適用於偵錯的資訊。

這個方法會在等候終止時傳回,可能是當收到任何句柄的訊號或發生逾時時。 如果在呼叫期間收到多個物件的訊號,傳回值會是訊號對象的陣列索引,且所有訊號物件的索引值最小。

等候句柄的最大數目為 64,如果目前線程處於 STA 狀態,則為 63。

結束內容

exitContext除非從非預設 Managed 內容內呼叫這個方法,否則參數不會有任何作用。 如果您的線程位於衍生自 ContextBoundObject之類別實例的呼叫內,則Managed內容可以是非預設的。 即使您目前正在不是衍生自 ContextBoundObject的類別上執行方法,例如 String,如果 ContextBoundObject 位於目前應用程式域中的堆疊上,您也可以在非預設內容中。

當您的程式代碼在非預設內容中執行時,指定 trueexitContext 會導致線程結束非預設受控內容 (,也就是在執行此方法之前轉換至默認內容) 。 呼叫這個方法之後,線程會傳回原始的非預設內容。

當內容系結類別具有 SynchronizationAttribute 屬性時,結束內容可能會很有用。 在此情況下,類別成員的所有呼叫都會自動同步處理,而同步處理網域則是類別的整個程式代碼主體。 如果成員呼叫堆疊中的程式代碼呼叫這個方法並指定 trueexitContext,線程會結束同步處理網域,這允許在呼叫物件的任何成員時封鎖的線程繼續進行。 當這個方法傳回時,進行呼叫的線程必須等候重新進入同步處理網域。

適用於

WaitAny(WaitHandle[], TimeSpan, Boolean)

Source:
WaitHandle.cs
Source:
WaitHandle.cs
Source:
WaitHandle.cs

等候指定陣列中的所有項目都收到信號,使用 TimeSpan 來指定時間間隔,並指定是否要先離開同步處理網域,再開始等候。

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

參數

waitHandles
WaitHandle[]

WaitHandle 陣列,包含目前執行個體將等候的物件。

timeout
TimeSpan

TimeSpan,代表等候毫秒數;或是 TimeSpan,代表無限期等候的 -1 毫秒。

exitContext
Boolean

true 表示在等候 (如果在同步內容中) 前結束內容的同步處理網域,並於之後重新取得,否則為 false

傳回

滿足等候條件之物件的陣列索引;如果沒有物件滿足等候條件,而且已經過相當於 timeout 的時間間隔,則為 WaitTimeout

例外狀況

waitHandles 參數為 null

-或-

waitHandles 陣列中的一或多個物件為 null

waitHandles 中的物件數目超過系統允許的數目。

waitHandles 是不具有項目的陣列,且 .NET Framework 版本為 1.0 或 1.1。

timeout 為 -1 毫秒以外的負數,表示無限逾時。

-或-

timeout 大於 Int32.MaxValue

由於執行緒結束時未釋放 Mutex,已完成等候。

waitHandles 是不具有元素的陣列,且 .NET Framework 版本為 2.0 (含) 以後版本。

waitHandles 陣列在另一個應用程式定義域中包含 WaitHandle 的 Transparent Proxy。

範例

下列程式代碼範例示範如何使用線程集區同時搜尋多個磁碟上的檔案。 如需空間考慮,只會搜尋每個磁碟的根目錄。

using namespace System;
using namespace System::IO;
using namespace System::Threading;
ref class Search
{
private:

   // Maintain state information to pass to FindCallback.
   ref class State
   {
   public:
      AutoResetEvent^ autoEvent;
      String^ fileName;
      State( AutoResetEvent^ autoEvent, String^ fileName )
         : autoEvent( autoEvent ), fileName( fileName )
      {}

   };


public:
   array<AutoResetEvent^>^autoEvents;
   array<String^>^diskLetters;

   // Search for stateInfo->fileName.
   void FindCallback( Object^ state )
   {
      State^ stateInfo = dynamic_cast<State^>(state);
      
      // Signal if the file is found.
      if ( File::Exists( stateInfo->fileName ) )
      {
         stateInfo->autoEvent->Set();
      }
   }

   Search()
   {
      
      // Retrieve an array of disk letters.
      diskLetters = Environment::GetLogicalDrives();
      autoEvents = gcnew array<AutoResetEvent^>(diskLetters->Length);
      for ( int i = 0; i < diskLetters->Length; i++ )
      {
         autoEvents[ i ] = gcnew AutoResetEvent( false );

      }
   }


   // Search for fileName in the root directory of all disks.
   void FindFile( String^ fileName )
   {
      for ( int i = 0; i < diskLetters->Length; i++ )
      {
         Console::WriteLine(  "Searching for {0} on {1}.", fileName, diskLetters[ i ] );
         ThreadPool::QueueUserWorkItem( gcnew WaitCallback( this, &Search::FindCallback ), gcnew State( autoEvents[ i ],String::Concat( diskLetters[ i ], fileName ) ) );

      }
      
      // Wait for the first instance of the file to be found.
      int index = WaitHandle::WaitAny( autoEvents, TimeSpan(0,0,3), false );
      if ( index == WaitHandle::WaitTimeout )
      {
         Console::WriteLine( "\n{0} not found.", fileName );
      }
      else
      {
         Console::WriteLine( "\n{0} found on {1}.", fileName, diskLetters[ index ] );
      }
   }

};

int main()
{
   Search^ search = gcnew Search;
   search->FindFile( "SomeFile.dat" );
}
using System;
using System.IO;
using System.Threading;

class Test
{
    static void Main()
    {
        Search search = new Search();
        search.FindFile("SomeFile.dat");
    }
}

class Search
{
    // Maintain state information to pass to FindCallback.
    class State
    {
        public AutoResetEvent autoEvent;
        public string         fileName;

        public State(AutoResetEvent autoEvent, string fileName)
        {
            this.autoEvent    = autoEvent;
            this.fileName     = fileName;
        }
    }

    AutoResetEvent[] autoEvents;
    String[] diskLetters;

    public Search()
    {
        // Retrieve an array of disk letters.
        diskLetters = Environment.GetLogicalDrives();

        autoEvents = new AutoResetEvent[diskLetters.Length];
        for(int i = 0; i < diskLetters.Length; i++)
        {
            autoEvents[i] = new AutoResetEvent(false);
        }
    }

    // Search for fileName in the root directory of all disks.
    public void FindFile(string fileName)
    {
        for(int i = 0; i < diskLetters.Length; i++)
        {
            Console.WriteLine("Searching for {0} on {1}.",
                fileName, diskLetters[i]);
            ThreadPool.QueueUserWorkItem(
                new WaitCallback(FindCallback), 
                new State(autoEvents[i], diskLetters[i] + fileName));
        }

        // Wait for the first instance of the file to be found.
        int index = WaitHandle.WaitAny(
            autoEvents, new TimeSpan(0, 0, 3), false);
        if(index == WaitHandle.WaitTimeout)
        {
            Console.WriteLine("\n{0} not found.", fileName);
        }
        else
        {
            Console.WriteLine("\n{0} found on {1}.", fileName,
                diskLetters[index]);
        }
    }

    // Search for stateInfo.fileName.
    void FindCallback(object state)
    {
        State stateInfo = (State)state;

        // Signal if the file is found.
        if(File.Exists(stateInfo.fileName))
        {
            stateInfo.autoEvent.Set();
        }
    }
}
Imports System.IO
Imports System.Threading

Public Class Test

    <MTAThread> _
    Shared Sub Main()
        Dim search As New Search()
        search.FindFile("SomeFile.dat")
    End Sub    
End Class

Public Class Search

    ' Maintain state information to pass to FindCallback.
    Class State
        Public autoEvent As AutoResetEvent 
        Public fileName As String         

        Sub New(anEvent As AutoResetEvent, fName As String)
            autoEvent = anEvent
            fileName = fName
        End Sub
    End Class

    Dim autoEvents() As AutoResetEvent
    Dim diskLetters() As String

    Sub New()

        ' Retrieve an array of disk letters.
        diskLetters = Environment.GetLogicalDrives()

        autoEvents = New AutoResetEvent(diskLetters.Length - 1) {}
        For i As Integer = 0 To diskLetters.Length - 1
            autoEvents(i) = New AutoResetEvent(False)
        Next i
    End Sub    
    
    ' Search for fileName in the root directory of all disks.
    Sub FindFile(fileName As String)
        For i As Integer = 0 To diskLetters.Length - 1
            Console.WriteLine("Searching for {0} on {1}.", _
                fileName, diskLetters(i))
        
            ThreadPool.QueueUserWorkItem(AddressOf FindCallback, _ 
                New State(autoEvents(i), diskLetters(i) & fileName))
        Next i

        ' Wait for the first instance of the file to be found.
        Dim index As Integer = WaitHandle.WaitAny( _
            autoEvents, New TimeSpan(0, 0, 3), False)
        If index = WaitHandle.WaitTimeout
            Console.WriteLine(vbCrLf & "{0} not found.", fileName)
        Else
            Console.WriteLine(vbCrLf & "{0} found on {1}.", _
                fileName, diskLetters(index))
        End If
    End Sub

    ' Search for stateInfo.fileName.
    Sub FindCallback(state As Object)
        Dim stateInfo As State = DirectCast(state, State)

        ' Signal if the file is found.
        If File.Exists(stateInfo.fileName) Then
            stateInfo.autoEvent.Set()
        End If
    End Sub

End Class

備註

如果 timeout 為零,則方法不會封鎖。 它會測試等候句柄的狀態,並立即傳回。

只有在因為放棄的 mutex 而等候完成時,方法 WaitAny 才會擲 AbandonedMutexException 回 。 如果 waitHandles 包含索引編號低於已放棄 Mutex 的已釋放 Mutex,則 WaitAny 方法會正常完成,而且不會擲回例外狀況。 已放棄的 Mutex 通常表示嚴重的程式代碼撰寫錯誤。 在全系統 Mutex 的情況下,它可能表示應用程式已突然終止 (例如,使用 Windows 任務管理員) 。 例外狀況包含適用於偵錯的資訊。

當等候終止時,這個方法會傳回當收到任何句柄的訊號或發生逾時時。 如果在呼叫期間收到多個物件的訊號,傳回值會是訊號對象的陣列索引,且所有訊號物件的索引值最小。

等候句柄的最大數目為 64,如果目前線程處於 STA 狀態,則為 63。

最大 timeout 值為 Int32.MaxValue

結束內容

exitContext除非從非預設 Managed 內容內呼叫這個方法,否則參數不會有任何作用。 如果您的線程位於衍生自 ContextBoundObject之類別實例的呼叫內,則Managed內容可以是非預設的。 即使您目前正在不是衍生自 ContextBoundObject的類別上執行方法,例如 String,如果 ContextBoundObject 位於目前應用程式域中的堆疊上,您也可以在非預設內容中。

當您的程式代碼在非預設內容中執行時,指定 trueexitContext 會導致線程結束非預設受控內容 (,也就是在執行此方法之前轉換至默認內容) 。 呼叫這個方法之後,線程會傳回原始的非預設內容。

當內容系結類別具有 SynchronizationAttribute 屬性時,結束內容可能會很有用。 在此情況下,類別成員的所有呼叫都會自動同步處理,而同步處理網域則是類別的整個程式代碼主體。 如果成員呼叫堆疊中的程式代碼呼叫這個方法並指定 trueexitContext,線程會結束同步處理網域,這允許在呼叫物件的任何成員時封鎖的線程繼續進行。 當這個方法傳回時,進行呼叫的線程必須等候重新進入同步處理網域。

適用於