WaitHandle.WaitOne Method (Int32) (System.Threading)

Switch View :
ScriptFree
.NET Framework Class Library
WaitHandle.WaitOne Method (Int32)

Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)
Syntax

Visual Basic
Public Overridable Function WaitOne ( _
	millisecondsTimeout As Integer _
) As Boolean
C#
public virtual bool WaitOne(
	int millisecondsTimeout
)
Visual C++
public:
virtual bool WaitOne(
	int millisecondsTimeout
)
F#
abstract WaitOne : 
        millisecondsTimeout:int -> bool 
override WaitOne : 
        millisecondsTimeout:int -> bool 

Parameters

millisecondsTimeout
Type: System.Int32
The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.

Return Value

Type: System.Boolean
true if the current instance receives a signal; otherwise, false.
Exceptions

Exception Condition
ObjectDisposedException

The current instance has already been disposed.

ArgumentOutOfRangeException

millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.

AbandonedMutexException

The wait completed because a thread exited without releasing a mutex. This exception is not thrown on Windows 98 or Windows Millennium Edition.

InvalidOperationException

The current instance is a transparent proxy for a WaitHandle in another application domain.

Remarks

If millisecondsTimeout is zero, the method does not block. It tests the state of the wait handle and returns immediately.

The caller of this method blocks until the current instance receives a signal or a time-out occurs. Use this method to block until a WaitHandle receives a signal from another thread, such as is generated when an asynchronous operation completes. For more information, see the IAsyncResult interface.

Override this method to customize the behavior of derived classes.

Calling this method overload is the same as calling the WaitOne(Int32, Boolean) overload and specifying false for exitContext.

Examples

The following code example shows how to use a wait handle to keep a process from terminating while it waits for a background thread to finish executing.

Visual Basic

Imports System
Imports System.Threading

Public Class WaitOne

    Shared autoEvent As New AutoResetEvent(False)

    <MTAThread> _
    Shared Sub Main()
        Console.WriteLine("Main starting.")

        ThreadPool.QueueUserWorkItem(AddressOf WorkMethod, autoEvent)

        ' Wait for work method to signal.
        If autoEvent.WaitOne(1000) Then
            Console.WriteLine("Work method signaled.")
        Else
            Console.WriteLine("Timed out waiting for work " & _
                "method to signal.")
        End If

        Console.WriteLine("Main ending.")
    End Sub

    Shared Sub WorkMethod(stateInfo As Object) 
        Console.WriteLine("Work starting.")

        ' Simulate time spent working.
        Thread.Sleep(New Random().Next(100, 2000))

        ' Signal that work is finished.
        Console.WriteLine("Work ending.")
        CType(stateInfo, AutoResetEvent).Set()
    End Sub

End Class


C#

using System;
using System.Threading;

class WaitOne
{
    static AutoResetEvent autoEvent = new AutoResetEvent(false);

    static void Main()
    {
        Console.WriteLine("Main starting.");

        ThreadPool.QueueUserWorkItem(
            new WaitCallback(WorkMethod), autoEvent);

        // Wait for work method to signal.
        if(autoEvent.WaitOne(1000))
        {
            Console.WriteLine("Work method signaled.");
        }
        else
        {
            Console.WriteLine("Timed out waiting for work " +
                "method to signal.");
        }
        Console.WriteLine("Main ending.");
    }

    static void WorkMethod(object stateInfo) 
    {
        Console.WriteLine("Work starting.");

        // Simulate time spent working.
        Thread.Sleep(new Random().Next(100, 2000));

        // Signal that work is finished.
        Console.WriteLine("Work ending.");
        ((AutoResetEvent)stateInfo).Set();
    }
}


Visual C++

using namespace System;
using namespace System::Threading;
ref class WaitOne
{
private:
   WaitOne(){}


public:
   static void WorkMethod( Object^ stateInfo )
   {
      Console::WriteLine( "Work starting." );

      // Simulate time spent working.
      Thread::Sleep( (gcnew Random)->Next( 100, 2000 ) );

      // Signal that work is finished.
      Console::WriteLine( "Work ending." );
      dynamic_cast<AutoResetEvent^>(stateInfo)->Set();
   }

};

int main()
{
   Console::WriteLine( "Main starting." );
   AutoResetEvent^ autoEvent = gcnew AutoResetEvent( false );
   ThreadPool::QueueUserWorkItem( gcnew WaitCallback( &WaitOne::WorkMethod ), autoEvent );

   // Wait for work method to signal.
   if ( autoEvent->WaitOne( 1000 ) )
   {
      Console::WriteLine( "Work method signaled." );
   }
   else
   {
      Console::WriteLine( "Timed out waiting for work "
      "method to signal." );
   }

   Console::WriteLine( "Main ending." );
}



Version Information

.NET Framework

Supported in: 4, 3.5 SP1, 3.0 SP2, 2.0 SP2

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
See Also

Reference

Community Content

EricLaw [MSFT]
Warning: Requires v2 SP2!
Warning 2 CA1903 : Microsoft.Portability : Member 'frmViewer.Main(string[])' uses member 'WaitHandle.WaitOne(int)'. Because this member was introduced in .NET Framework 2.0 Service Pack 2, which was not included in the project's target framework, .NET Framework 2.0, your application may fail to run on systems without this service pack installed. 

Instead, just call WaitOne(int32, false) which doesn't require SP2.