Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
Thread Class
Thread Methods
Sleep Method
 Sleep Method (Int32)
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Thread..::.Sleep Method (Int32)

Suspends the current thread for a specified time.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
Public Shared Sub Sleep ( _
    millisecondsTimeout As Integer _
)
Visual Basic (Usage)
Dim millisecondsTimeout As Integer

Thread.Sleep(millisecondsTimeout)
C#
public static void Sleep(
    int millisecondsTimeout
)
Visual C++
public:
static void Sleep(
    int millisecondsTimeout
)
JScript
public static function Sleep(
    millisecondsTimeout : int
)

Parameters

millisecondsTimeout
Type: System..::.Int32
The number of milliseconds for which the thread is blocked. Specify zero (0) to indicate that this thread should be suspended to allow other waiting threads to execute. Specify Infinite to block the thread indefinitely.
ExceptionCondition
ArgumentOutOfRangeException

The time-out value is negative and is not equal to Infinite.

The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.

This method does not perform standard COM and SendMessage pumping.

NoteNote:

If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.

The following code example demonstrates a sleeping thread.

Visual Basic
Imports Microsoft.VisualBasic
Imports System
Imports System.Threading

Public Class ApartmentTest

    <MTAThread> _
    Shared Sub Main()

        Dim newThread As Thread = New Thread(AddressOf ThreadMethod)
        newThread.SetApartmentState(ApartmentState.MTA)

        ' The following line is ignored since 
        ' ApartmentState can only be set once.
        newThread.SetApartmentState(ApartmentState.STA)

        Console.WriteLine("ThreadState: {0}, ApartmentState: {1}", _
            newThread.ThreadState, newThread.GetApartmentState())

        newThread.Start()

        ' Wait for newThread to start and go to sleep.
        Thread.Sleep(300)
        Try
            ' This causes an exception since newThread is sleeping.
            newThread.SetApartmentState(ApartmentState.STA)
        Catch stateException As ThreadStateException
            Console.WriteLine(vbCrLf & "{0} caught:" & vbCrLf & _
                "Thread is not In the Unstarted or Running state.", _
                stateException.GetType().Name)
            Console.WriteLine("ThreadState: {0}, ApartmentState: " & _
                "{1}", newThread.ThreadState, newThread.GetApartmentState())
        End Try

    End Sub

    Shared Sub ThreadMethod()
        Thread.Sleep(1000)
    End Sub

End Class
C#
using System;
using System.Threading;

class ApartmentTest
{
    static void Main()
    {
        Thread newThread = 
            new Thread(new ThreadStart(ThreadMethod));
        newThread.SetApartmentState(ApartmentState.MTA);

        // The following line is ignored since 
        // ApartmentState can only be set once.
        newThread.SetApartmentState(ApartmentState.STA);

        Console.WriteLine("ThreadState: {0}, ApartmentState: {1}", 
            newThread.ThreadState, newThread.ApartmentState);

        newThread.Start();

        // Wait for newThread to start and go to sleep.
        Thread.Sleep(300);
        try
        {
            // This causes an exception since newThread is sleeping.
            newThread.SetApartmentState(ApartmentState.STA);
        }
        catch(ThreadStateException stateException)
        {
            Console.WriteLine("\n{0} caught:\n" +
                "Thread is not in the Unstarted or Running state.", 
                stateException.GetType().Name);
            Console.WriteLine("ThreadState: {0}, ApartmentState: {1}",
                newThread.ThreadState, newThread.GetApartmentState());
        }
    }

    static void ThreadMethod()
    {
        Thread.Sleep(1000);
    }
}
Visual C++
using namespace System;
using namespace System::Threading;
ref class ApartmentTest
{
public:
   static void ThreadMethod()
   {
      Thread::Sleep( 1000 );
   }

};

int main()
{
   Thread^ newThread = gcnew Thread( gcnew ThreadStart( &ApartmentTest::ThreadMethod ) );
   newThread->SetApartmentState(ApartmentState::MTA);

   // The following line is ignored since 
   // ApartmentState can only be set once.
   newThread->SetApartmentState(ApartmentState::STA);
   Console::WriteLine( "ThreadState: {0}, ApartmentState: {1}", newThread->ThreadState.ToString(), newThread->GetApartmentState().ToString() );
   newThread->Start();

   // Wait for newThread to start and go to sleep.
   Thread::Sleep( 300 );
   try
   {

      // This causes an exception since newThread is sleeping.
      newThread->SetApartmentState(ApartmentState::STA);
   }
   catch ( ThreadStateException^ stateException ) 
   {
      Console::WriteLine( "\n{0} caught:\n"
      "Thread is not in the Unstarted or Running state.", stateException->GetType()->Name );
      Console::WriteLine( "ThreadState: {0}, ApartmentState: {1}", newThread->ThreadState.ToString(), newThread->GetApartmentState().ToString() );
   }

}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
How to get the line of the code running in Visual Studio 2008?      arabcoder   |   Edit   |   Show History
like the ansi C __LINE__ ?, thank you

Ghazi, from Libanon
Forcing of a Context Switch      LukeSkywalker   |   Edit   |   Show History
On page 168 (first edition) of Joe Duffy's Concurrent Programming on Windows (link below), Joe states that "if there are runnable threads at a lower priority [and the duration argument is 0], the calling thread will continue running instead of yielding to the other threads" which introduces a potential problem.

It is common to call Sleep(0) to 'force' a context switch, sometimes to avoid deadlocks, however the switch may not take place if the thread has a higher priority than its peers.


Further, Joe writes "passing a value greater than 0 for the argument unconditionally results in a context switch".

http://www.amazon.co.uk/gp/product/032143482X?ie=UTF8&tag=lukepupl-21&linkCode=as2&camp=1634&creative=19450&creativeASIN=032143482X


Also note that the time's accuracy is affected by the granularity of the system clock - commonly 10ms. See Interrupt Rate Granularity at the following address for an emprical example:

http://software.intel.com/en-us/articles/cpu-power-utilization-on-intel-architectures/
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker