Share via


WaitHandle.SignalAndWait Metode

Definisi

Sinyal satu WaitHandle dan menunggu di yang lain.

Overload

SignalAndWait(WaitHandle, WaitHandle)

Sinyal satu WaitHandle dan menunggu di yang lain.

SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean)

Memberi sinyal dan WaitHandle menunggu di yang lain, menentukan interval waktu habis sebagai bilangan bulat bertanda tangan 32-bit dan menentukan apakah akan keluar dari domain sinkronisasi untuk konteks sebelum memasukkan tunggu.

SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean)

Memberi sinyal dan WaitHandle menunggu di yang lain, menentukan interval waktu habis sebagai TimeSpan dan menentukan apakah akan keluar dari domain sinkronisasi untuk konteks sebelum memasukkan tunggu.

SignalAndWait(WaitHandle, WaitHandle)

Sumber:
WaitHandle.cs
Sumber:
WaitHandle.cs
Sumber:
WaitHandle.cs

Sinyal satu WaitHandle dan menunggu di yang lain.

public:
 static bool SignalAndWait(System::Threading::WaitHandle ^ toSignal, System::Threading::WaitHandle ^ toWaitOn);
public static bool SignalAndWait (System.Threading.WaitHandle toSignal, System.Threading.WaitHandle toWaitOn);
static member SignalAndWait : System.Threading.WaitHandle * System.Threading.WaitHandle -> bool
Public Shared Function SignalAndWait (toSignal As WaitHandle, toWaitOn As WaitHandle) As Boolean

Parameter

toSignal
WaitHandle

Sinyal WaitHandle untuk.

toWaitOn
WaitHandle

Menunggu WaitHandle .

Mengembalikan

true jika sinyal dan penantian berhasil diselesaikan; jika penantian tidak selesai, metode tidak akan kembali.

Pengecualian

toSignaladalah null.

-atau-

toWaitOnadalah null.

Metode ini dipanggil pada utas dalam STA status .

toSignal adalah semaphore, dan sudah memiliki jumlah penuh.

Penantian selesai karena utas keluar tanpa melepaskan mutex.

Contoh

Contoh kode berikut menggunakan metode kelebihan beban untuk memungkinkan utas utama memberi sinyal utas SignalAndWait(WaitHandle, WaitHandle) yang diblokir lalu menunggu hingga utas menyelesaikan tugas.

Contohnya memulai lima utas, memungkinkan mereka memblokir pada yang EventWaitHandle dibuat dengan EventResetMode.AutoReset bendera , lalu merilis satu utas setiap kali pengguna menekan tombol ENTER. Contohnya kemudian mengantre lima utas lain dan merilis semuanya menggunakan yang EventWaitHandle dibuat dengan EventResetMode.ManualReset bendera .

using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // The EventWaitHandle used to demonstrate the difference
   // between AutoReset and ManualReset synchronization events.
   //
   static EventWaitHandle^ ewh;

   // A counter to make sure all threads are started and
   // blocked before any are released. A Long is used to show
   // the use of the 64-bit Interlocked methods.
   //
   static __int64 threadCount = 0;

   // An AutoReset event that allows the main thread to block
   // until an exiting thread has decremented the count.
   //
   static EventWaitHandle^ clearCount =
      gcnew EventWaitHandle( false,EventResetMode::AutoReset );

public:
   [MTAThread]
   static void main()
   {
      // Create an AutoReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::AutoReset );
      
      // Create and start five numbered threads. Use the
      // ParameterizedThreadStart delegate, so the thread
      // number can be passed as an argument to the Start
      // method.
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      // When multiple threads use a 64-bit value on a 32-bit
      // system, you must access the value through the
      // Interlocked class to guarantee thread safety.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Release one thread each time the user presses ENTER,
      // until all threads have been released.
      //
      while ( Interlocked::Read( threadCount ) > 0 )
      {
         Console::WriteLine( L"Press ENTER to release a waiting thread." );
         Console::ReadLine();
         
         // SignalAndWait signals the EventWaitHandle, which
         // releases exactly one thread before resetting,
         // because it was created with AutoReset mode.
         // SignalAndWait then blocks on clearCount, to
         // allow the signaled thread to decrement the count
         // before looping again.
         //
         WaitHandle::SignalAndWait( ewh, clearCount );
      }
      Console::WriteLine();
      
      // Create a ManualReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::ManualReset );
      
      // Create and start five more numbered threads.
      //
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Because the EventWaitHandle was created with
      // ManualReset mode, signaling it releases all the
      // waiting threads.
      //
      Console::WriteLine( L"Press ENTER to release the waiting threads." );
      Console::ReadLine();
      ewh->Set();

   }

   static void ThreadProc( Object^ data )
   {
      int index = static_cast<Int32>(data);

      Console::WriteLine( L"Thread {0} blocks.", data );
      // Increment the count of blocked threads.
      Interlocked::Increment( threadCount );
      
      // Wait on the EventWaitHandle.
      ewh->WaitOne();

      Console::WriteLine( L"Thread {0} exits.", data );
      // Decrement the count of blocked threads.
      Interlocked::Decrement( threadCount );
      
      // After signaling ewh, the main thread blocks on
      // clearCount until the signaled thread has
      // decremented the count. Signal it now.
      //
      clearCount->Set();
   }
};
using System;
using System.Threading;

public class Example
{
    // The EventWaitHandle used to demonstrate the difference
    // between AutoReset and ManualReset synchronization events.
    //
    private static EventWaitHandle ewh;

    // A counter to make sure all threads are started and
    // blocked before any are released. A Long is used to show
    // the use of the 64-bit Interlocked methods.
    //
    private static long threadCount = 0;

    // An AutoReset event that allows the main thread to block
    // until an exiting thread has decremented the count.
    //
    private static EventWaitHandle clearCount = 
        new EventWaitHandle(false, EventResetMode.AutoReset);

    [MTAThread]
    public static void Main()
    {
        // Create an AutoReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.AutoReset);

        // Create and start five numbered threads. Use the
        // ParameterizedThreadStart delegate, so the thread
        // number can be passed as an argument to the Start 
        // method.
        for (int i = 0; i <= 4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        // When multiple threads use a 64-bit value on a 32-bit
        // system, you must access the value through the
        // Interlocked class to guarantee thread safety.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Release one thread each time the user presses ENTER,
        // until all threads have been released.
        //
        while (Interlocked.Read(ref threadCount) > 0)
        {
            Console.WriteLine("Press ENTER to release a waiting thread.");
            Console.ReadLine();

            // SignalAndWait signals the EventWaitHandle, which
            // releases exactly one thread before resetting, 
            // because it was created with AutoReset mode. 
            // SignalAndWait then blocks on clearCount, to 
            // allow the signaled thread to decrement the count
            // before looping again.
            //
            WaitHandle.SignalAndWait(ewh, clearCount);
        }
        Console.WriteLine();

        // Create a ManualReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

        // Create and start five more numbered threads.
        //
        for(int i=0; i<=4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Because the EventWaitHandle was created with
        // ManualReset mode, signaling it releases all the
        // waiting threads.
        //
        Console.WriteLine("Press ENTER to release the waiting threads.");
        Console.ReadLine();
        ewh.Set();
    }

    public static void ThreadProc(object data)
    {
        int index = (int) data;

        Console.WriteLine("Thread {0} blocks.", data);
        // Increment the count of blocked threads.
        Interlocked.Increment(ref threadCount);

        // Wait on the EventWaitHandle.
        ewh.WaitOne();

        Console.WriteLine("Thread {0} exits.", data);
        // Decrement the count of blocked threads.
        Interlocked.Decrement(ref threadCount);

        // After signaling ewh, the main thread blocks on
        // clearCount until the signaled thread has 
        // decremented the count. Signal it now.
        //
        clearCount.Set();
    }
}
Imports System.Threading

Public Class Example

    ' The EventWaitHandle used to demonstrate the difference
    ' between AutoReset and ManualReset synchronization events.
    '
    Private Shared ewh As EventWaitHandle

    ' A counter to make sure all threads are started and
    ' blocked before any are released. A Long is used to show
    ' the use of the 64-bit Interlocked methods.
    '
    Private Shared threadCount As Long = 0

    ' An AutoReset event that allows the main thread to block
    ' until an exiting thread has decremented the count.
    '
    Private Shared clearCount As New EventWaitHandle(False, _
        EventResetMode.AutoReset)

    <MTAThread> _
    Public Shared Sub Main()

        ' Create an AutoReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.AutoReset)

        ' Create and start five numbered threads. Use the
        ' ParameterizedThreadStart delegate, so the thread
        ' number can be passed as an argument to the Start 
        ' method.
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        ' When multiple threads use a 64-bit value on a 32-bit
        ' system, you must access the value through the
        ' Interlocked class to guarantee thread safety.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Release one thread each time the user presses ENTER,
        ' until all threads have been released.
        '
        While Interlocked.Read(threadCount) > 0
            Console.WriteLine("Press ENTER to release a waiting thread.")
            Console.ReadLine()

            ' SignalAndWait signals the EventWaitHandle, which
            ' releases exactly one thread before resetting, 
            ' because it was created with AutoReset mode. 
            ' SignalAndWait then blocks on clearCount, to 
            ' allow the signaled thread to decrement the count
            ' before looping again.
            '
            WaitHandle.SignalAndWait(ewh, clearCount)
        End While
        Console.WriteLine()

        ' Create a ManualReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.ManualReset)

        ' Create and start five more numbered threads.
        '
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Because the EventWaitHandle was created with
        ' ManualReset mode, signaling it releases all the
        ' waiting threads.
        '
        Console.WriteLine("Press ENTER to release the waiting threads.")
        Console.ReadLine()
        ewh.Set()
        
    End Sub

    Public Shared Sub ThreadProc(ByVal data As Object)
        Dim index As Integer = CInt(data)

        Console.WriteLine("Thread {0} blocks.", data)
        ' Increment the count of blocked threads.
        Interlocked.Increment(threadCount)

        ' Wait on the EventWaitHandle.
        ewh.WaitOne()

        Console.WriteLine("Thread {0} exits.", data)
        ' Decrement the count of blocked threads.
        Interlocked.Decrement(threadCount)

        ' After signaling ewh, the main thread blocks on
        ' clearCount until the signaled thread has 
        ' decremented the count. Signal it now.
        '
        clearCount.Set()
    End Sub
End Class

Keterangan

Operasi ini tidak dijamin sebagai atomik. Setelah alur saat ini memberi sinyal toSignal tetapi sebelum menunggu di toWaitOn, utas yang berjalan pada prosesor lain mungkin memberi sinyal toWaitOn atau menunggu di atasnya.

Berlaku untuk

SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean)

Sumber:
WaitHandle.cs
Sumber:
WaitHandle.cs
Sumber:
WaitHandle.cs

Memberi sinyal dan WaitHandle menunggu di yang lain, menentukan interval waktu habis sebagai bilangan bulat bertanda tangan 32-bit dan menentukan apakah akan keluar dari domain sinkronisasi untuk konteks sebelum memasukkan tunggu.

public:
 static bool SignalAndWait(System::Threading::WaitHandle ^ toSignal, System::Threading::WaitHandle ^ toWaitOn, int millisecondsTimeout, bool exitContext);
public static bool SignalAndWait (System.Threading.WaitHandle toSignal, System.Threading.WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext);
static member SignalAndWait : System.Threading.WaitHandle * System.Threading.WaitHandle * int * bool -> bool
Public Shared Function SignalAndWait (toSignal As WaitHandle, toWaitOn As WaitHandle, millisecondsTimeout As Integer, exitContext As Boolean) As Boolean

Parameter

toSignal
WaitHandle

Sinyal WaitHandle untuk.

toWaitOn
WaitHandle

Menunggu WaitHandle .

millisecondsTimeout
Int32

Bilangan bulat yang mewakili interval untuk menunggu. Jika nilainya adalah Infinite, yaitu, -1, penantian tidak terbatas.

exitContext
Boolean

true untuk keluar dari domain sinkronisasi untuk konteks sebelum menunggu (jika dalam konteks yang disinkronkan), dan memperolehnya kembali setelahnya; jika tidak, false.

Mengembalikan

true jika sinyal dan penantian berhasil diselesaikan, atau false jika sinyal selesai tetapi waktu tunggu habis.

Pengecualian

toSignaladalah null.

-atau-

toWaitOnadalah null.

Metode ini dipanggil pada utas dalam STA status .

WaitHandle tidak dapat disinyalkan karena akan melebihi jumlah maksimumnya.

millisecondsTimeout adalah angka negatif selain -1, yang menunjukkan waktu habis yang tak terbatas.

Penantian selesai karena utas keluar tanpa melepaskan mutex.

Keterangan

Operasi ini tidak dijamin sebagai atomik. Setelah alur saat ini memberi sinyal toSignal tetapi sebelum menunggu di toWaitOn, utas yang berjalan pada prosesor lain mungkin memberi sinyal toWaitOn atau menunggu di atasnya.

Jika millisecondsTimeout nol, metode tidak memblokir. Ini menguji status toWaitOn dan segera kembali.

Keluar dari konteks

Parameter exitContext tidak berpengaruh kecuali metode ini dipanggil dari dalam konteks terkelola nondefault. Konteks terkelola dapat menjadi nondefault jika utas Anda berada di dalam panggilan ke instans kelas yang berasal dari ContextBoundObject. Bahkan jika saat ini Anda menjalankan metode pada kelas yang tidak berasal dari ContextBoundObject, seperti String, Anda dapat berada dalam konteks nondefault jika ContextBoundObject ada di tumpukan Anda di domain aplikasi saat ini.

Saat kode Anda dijalankan dalam konteks nondefault, menentukan true penyebab exitContext utas keluar dari konteks terkelola nondefault (yaitu, untuk beralih ke konteks default) sebelum menjalankan metode ini. Utas kembali ke konteks nondefault asli setelah panggilan ke metode ini selesai.

Keluar dari konteks dapat berguna ketika kelas yang terikat konteks memiliki SynchronizationAttribute atribut . Dalam hal ini, semua panggilan ke anggota kelas secara otomatis disinkronkan, dan domain sinkronisasi adalah seluruh isi kode untuk kelas . Jika kode dalam tumpukan panggilan anggota memanggil metode ini dan menentukan untuk exitContext, utas true keluar dari domain sinkronisasi, yang memungkinkan utas yang diblokir pada panggilan ke anggota objek mana pun untuk melanjutkan. Ketika metode ini kembali, utas yang melakukan panggilan harus menunggu untuk masuk kembali ke domain sinkronisasi.

Berlaku untuk

SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean)

Sumber:
WaitHandle.cs
Sumber:
WaitHandle.cs
Sumber:
WaitHandle.cs

Memberi sinyal dan WaitHandle menunggu di yang lain, menentukan interval waktu habis sebagai TimeSpan dan menentukan apakah akan keluar dari domain sinkronisasi untuk konteks sebelum memasukkan tunggu.

public:
 static bool SignalAndWait(System::Threading::WaitHandle ^ toSignal, System::Threading::WaitHandle ^ toWaitOn, TimeSpan timeout, bool exitContext);
public static bool SignalAndWait (System.Threading.WaitHandle toSignal, System.Threading.WaitHandle toWaitOn, TimeSpan timeout, bool exitContext);
static member SignalAndWait : System.Threading.WaitHandle * System.Threading.WaitHandle * TimeSpan * bool -> bool
Public Shared Function SignalAndWait (toSignal As WaitHandle, toWaitOn As WaitHandle, timeout As TimeSpan, exitContext As Boolean) As Boolean

Parameter

toSignal
WaitHandle

Sinyal WaitHandle untuk.

toWaitOn
WaitHandle

Menunggu WaitHandle .

timeout
TimeSpan

TimeSpan yang mewakili interval untuk menunggu. Jika nilainya adalah -1, penantian tidak terbatas.

exitContext
Boolean

true untuk keluar dari domain sinkronisasi untuk konteks sebelum menunggu (jika dalam konteks yang disinkronkan), dan memperolehnya kembali setelahnya; jika tidak, false.

Mengembalikan

true jika sinyal dan penantian berhasil diselesaikan, atau false jika sinyal selesai tetapi waktu tunggu habis.

Pengecualian

toSignaladalah null.

-atau-

toWaitOnadalah null.

Metode ini dipanggil pada utas dalam STA status .

toSignal adalah semaphore, dan sudah memiliki jumlah penuh.

timeout mengevaluasi ke jumlah negatif milidetik selain -1.

-atau-

timeout lebih besar dari Int32.MaxValue.

Penantian selesai karena utas keluar tanpa melepaskan mutex.

Keterangan

Operasi ini tidak dijamin sebagai atomik. Setelah alur saat ini memberi sinyal toSignal tetapi sebelum menunggu di toWaitOn, utas yang berjalan pada prosesor lain mungkin memberi sinyal toWaitOn atau menunggu di atasnya.

Nilai maksimum untuk timeout adalah Int32.MaxValue.

Jika timeout nol, metode tidak memblokir. Ini menguji status toWaitOn dan segera kembali.

Keluar dari konteks

Parameter exitContext tidak berpengaruh kecuali metode ini dipanggil dari dalam konteks terkelola nondefault. Konteks terkelola dapat menjadi nondefault jika utas Anda berada di dalam panggilan ke instans kelas yang berasal dari ContextBoundObject. Bahkan jika saat ini Anda menjalankan metode pada kelas yang tidak berasal dari ContextBoundObject, seperti String, Anda dapat berada dalam konteks nondefault jika ContextBoundObject ada di tumpukan Anda di domain aplikasi saat ini.

Saat kode Anda dijalankan dalam konteks nondefault, menentukan true penyebab exitContext utas keluar dari konteks terkelola nondefault (yaitu, untuk beralih ke konteks default) sebelum menjalankan metode ini. Utas kembali ke konteks nondefault asli setelah panggilan ke metode ini selesai.

Keluar dari konteks dapat berguna ketika kelas yang terikat konteks memiliki SynchronizationAttribute atribut . Dalam hal ini, semua panggilan ke anggota kelas secara otomatis disinkronkan, dan domain sinkronisasi adalah seluruh isi kode untuk kelas . Jika kode dalam tumpukan panggilan anggota memanggil metode ini dan menentukan untuk exitContext, utas true keluar dari domain sinkronisasi, yang memungkinkan utas yang diblokir pada panggilan ke anggota objek mana pun untuk melanjutkan. Ketika metode ini kembali, utas yang melakukan panggilan harus menunggu untuk masuk kembali ke domain sinkronisasi.

Berlaku untuk