Thread Class (System.Threading)

Switch View :
ScriptFree
.NET Framework Class Library
Thread Class

Creates and controls a thread, sets its priority, and gets its status.

Inheritance Hierarchy

System.Object
  System.Runtime.ConstrainedExecution.CriticalFinalizerObject
    System.Threading.Thread

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

Visual Basic
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
<ComVisibleAttribute(True)> _
Public NotInheritable Class Thread _
	Inherits CriticalFinalizerObject _
	Implements _Thread
C#
[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
public sealed class Thread : CriticalFinalizerObject, 
	_Thread
Visual C++
[ClassInterfaceAttribute(ClassInterfaceType::None)]
[ComVisibleAttribute(true)]
public ref class Thread sealed : public CriticalFinalizerObject, 
	_Thread
F#
[<Sealed>]
[<ClassInterfaceAttribute(ClassInterfaceType.None)>]
[<ComVisibleAttribute(true)>]
type Thread =  
    class
        inherit CriticalFinalizerObject
        interface _Thread
    end

The Thread type exposes the following members.

Constructors

  Name Description
Public method Thread(ParameterizedThreadStart) Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started.
Public method Supported by the XNA Framework Supported by Portable Class Library Thread(ThreadStart) Initializes a new instance of the Thread class.
Public method Thread(ParameterizedThreadStart, Int32) Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started and specifying the maximum stack size for the thread.
Public method Supported by the XNA Framework Thread(ThreadStart, Int32) Initializes a new instance of the Thread class, specifying the maximum stack size for the thread.
Top
Properties

  Name Description
Public property ApartmentState Obsolete. Gets or sets the apartment state of this thread.
Public property Static member CurrentContext Gets the current context in which the thread is executing.
Public property Supported by Portable Class Library CurrentCulture Gets or sets the culture for the current thread.
Public property Static member CurrentPrincipal Gets or sets the thread's current principal (for role-based security).
Public property Static member Supported by the XNA Framework Supported by Portable Class Library CurrentThread Gets the currently running thread.
Public property Supported by Portable Class Library CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.
Public property ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread.
Public property IsAlive Gets a value indicating the execution status of the current thread.
Public property Supported by the XNA Framework Supported by Portable Class Library IsBackground Gets or sets a value indicating whether or not a thread is a background thread.
Public property IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool.
Public property Supported by the XNA Framework Supported by Portable Class Library ManagedThreadId Gets a unique identifier for the current managed thread.
Public property Supported by the XNA Framework Supported by Portable Class Library Name Gets or sets the name of the thread.
Public property Supported by the XNA Framework Priority Gets or sets a value indicating the scheduling priority of a thread.
Public property ThreadState Gets a value containing the states of the current thread.
Top
Methods

  Name Description
Public method Supported by the XNA Framework Abort() Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
Public method Supported by the XNA Framework Abort(Object) Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Calling this method usually terminates the thread.
Public method Static member Supported by the XNA Framework AllocateDataSlot Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
Public method Static member Supported by the XNA Framework AllocateNamedDataSlot Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
Public method Static member BeginCriticalRegion Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.
Public method Static member BeginThreadAffinity Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.
Public method DisableComObjectEagerCleanup Turns off automatic cleanup of runtime callable wrappers (RCW) for the current thread.
Public method Static member EndCriticalRegion Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.
Public method Static member EndThreadAffinity Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.
Public method Supported by the XNA Framework Supported by Portable Class Library Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by the XNA Framework Supported by Portable Class Library Finalize Releases all the resources used by the CriticalFinalizerObject class. (Inherited from CriticalFinalizerObject.)

In XNA Framework 3.0, this member is inherited from Object.Finalize().


In Portable Class Library Portable Class Library, this member is inherited from Object.Finalize().
Public method Static member Supported by the XNA Framework FreeNamedDataSlot Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
Public method GetApartmentState Returns an ApartmentState value indicating the apartment state.
Public method GetCompressedStack Obsolete. Returns a CompressedStack object that can be used to capture the stack for the current thread.
Public method Static member Supported by the XNA Framework GetData Retrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
Public method Static member Supported by the XNA Framework GetDomain Returns the current domain in which the current thread is running.
Public method Static member GetDomainID Returns a unique application domain identifier.
Public method Supported by the XNA Framework Supported by Portable Class Library GetHashCode Returns a hash code for the current thread. (Overrides Object.GetHashCode().)

In XNA Framework 3.0, this member is inherited from Object.GetHashCode().


In Portable Class Library Portable Class Library, this member is inherited from Object.GetHashCode().
Public method Static member Supported by the XNA Framework GetNamedDataSlot Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
Public method Supported by the XNA Framework Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Public method Interrupt Interrupts a thread that is in the WaitSleepJoin thread state.
Public method Supported by the XNA Framework Supported by Portable Class Library Join() Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping.
Public method Supported by the XNA Framework Supported by Portable Class Library Join(Int32) Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.
Public method Join(TimeSpan) Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.
Protected method Supported by the XNA Framework Supported by Portable Class Library MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Static member Supported by the XNA Framework Supported by Portable Class Library MemoryBarrier Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
Public method Static member ResetAbort Cancels an Abort requested for the current thread.
Public method Resume Obsolete. Resumes a thread that has been suspended.
Public method SetApartmentState Sets the apartment state of a thread before it is started.
Public method SetCompressedStack Obsolete. Applies a captured CompressedStack to the current thread.
Public method Static member Supported by the XNA Framework SetData Sets the data in the specified slot on the currently running thread, for that thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead.
Public method Supported by the XNA Framework SetProcessorAffinity In the .NET Compact Framework for Xbox 360, sets the processor affinity for a managed thread. Processor affinity determines the processors on which a thread runs.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Sleep(Int32) Suspends the current thread for a specified time.
Public method Static member Sleep(TimeSpan) Blocks the current thread for a specified time.
Public method Static member SpinWait Causes a thread to wait the number of times defined by the iterations parameter.
Public method Supported by the XNA Framework Supported by Portable Class Library Start() Causes the operating system to change the state of the current instance to ThreadState.Running.
Public method Start(Object) Causes the operating system to change the state of the current instance to ThreadState.Running, and optionally supplies an object containing data to be used by the method the thread executes.
Public method Suspend Obsolete. Either suspends the thread, or if the thread is already suspended, has no effect.
Public method Supported by the XNA Framework Supported by Portable Class Library ToString Returns a string that represents the current object. (Inherited from Object.)
Public method TrySetApartmentState Sets the apartment state of a thread before it is started.
Public method Static member VolatileRead(Byte) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(Double) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(Int16) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(Int32) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(Int64) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(IntPtr) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(Object) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(SByte) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(Single) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(UInt16) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(UInt32) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(UInt64) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileRead(UIntPtr) Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.
Public method Static member VolatileWrite(Byte, Byte) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(Double, Double) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(Int16, Int16) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(Int32, Int32) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(Int64, Int64) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(IntPtr, IntPtr) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(Object, Object) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(SByte, SByte) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(Single, Single) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(UInt16, UInt16) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(UInt32, UInt32) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(UInt64, UInt64) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member VolatileWrite(UIntPtr, UIntPtr) Writes a value to a field immediately, so that the value is visible to all processors in the computer.
Public method Static member Yield Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.
Top
Explicit Interface Implementations

  Name Description
Explicit interface implemetation Private method _Thread.GetIDsOfNames Maps a set of names to a corresponding set of dispatch identifiers.
Explicit interface implemetation Private method _Thread.GetTypeInfo Retrieves the type information for an object, which can then be used to get the type information for an interface.
Explicit interface implemetation Private method _Thread.GetTypeInfoCount Retrieves the number of type information interfaces that an object provides (either 0 or 1).
Explicit interface implemetation Private method _Thread.Invoke Provides access to properties and methods exposed by an object.
Top
Remarks

A process can create one or more threads to execute a portion of the program code associated with the process. Use a ThreadStart delegate or the ParameterizedThreadStart delegate to specify the program code executed by a thread. The ParameterizedThreadStart delegate allows you to pass data to the thread procedure.

For the duration of its existence, a thread is always in one or more of the states defined by ThreadState. A scheduling priority level, as defined by ThreadPriority, can be requested for a thread, but is not guaranteed to be honored by the operating system.

GetHashCode provides identification for managed threads. For the lifetime of your thread, it will not collide with the value from any other thread, regardless of the application domain from which you obtain the value.

Note Note

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

It is not necessary to retain a reference to a Thread object once you have started the thread. The thread continues to execute until the thread procedure is complete.

Important note Important

Beginning with the .NET Framework version 4, the behavior of some thread constructors is changed: Only fully trusted code can set the maximum stack size to a value that is greater than the default stack size (1 megabyte). If a larger value is specified when code is running with partial trust, the larger value is ignored and the default stack size is used. No exception is thrown. Code at any trust level can set the maximum stack size to a value that is less than the default stack size.

Examples

The following code example demonstrates simple threading functionality.

Visual Basic

Imports System
Imports System.Threading

' Simple threading scenario:  Start a Shared method running
' on a second thread.
Public Class ThreadExample
    ' The ThreadProc method is called when the thread starts.
    ' It loops ten times, writing to the console and yielding 
    ' the rest of its time slice each time, and then ends.
    Public Shared Sub ThreadProc()
        Dim i As Integer
        For i = 0 To 9
            Console.WriteLine("ThreadProc: {0}", i)
            ' Yield the rest of the time slice.
            Thread.Sleep(0)
        Next
    End Sub

    Public Shared Sub Main()
        Console.WriteLine("Main thread: Start a second thread.")
        ' The constructor for the Thread class requires a ThreadStart 
        ' delegate.  The Visual Basic AddressOf operator creates this
        ' delegate for you.
        Dim t As New Thread(AddressOf ThreadProc)

        ' Start ThreadProc.  Note that on a uniprocessor, the new 
        ' thread does not get any processor time until the main thread 
        ' is preempted or yields.  Uncomment the Thread.Sleep that 
        ' follows t.Start() to see the difference.
        t.Start()
        'Thread.Sleep(0)

        Dim i As Integer
        For i = 1 To 4
            Console.WriteLine("Main thread: Do some work.")
            Thread.Sleep(0)
        Next

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.")
        t.Join()
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.")
        Console.ReadLine()
    End Sub
End Class


C#

using System;
using System.Threading;

// Simple threading scenario:  Start a static method running
// on a second thread.
public class ThreadExample {
    // The ThreadProc method is called when the thread starts.
    // It loops ten times, writing to the console and yielding 
    // the rest of its time slice each time, and then ends.
    public static void ThreadProc() {
        for (int i = 0; i < 10; i++) {
            Console.WriteLine("ThreadProc: {0}", i);
            // Yield the rest of the time slice.
            Thread.Sleep(0);
        }
    }

    public static void Main() {
        Console.WriteLine("Main thread: Start a second thread.");
        // The constructor for the Thread class requires a ThreadStart 
        // delegate that represents the method to be executed on the 
        // thread.  C# simplifies the creation of this delegate.
        Thread t = new Thread(new ThreadStart(ThreadProc));

        // Start ThreadProc.  Note that on a uniprocessor, the new 
        // thread does not get any processor time until the main thread 
        // is preempted or yields.  Uncomment the Thread.Sleep that 
        // follows t.Start() to see the difference.
        t.Start();
        //Thread.Sleep(0);

        for (int i = 0; i < 4; i++) {
            Console.WriteLine("Main thread: Do some work.");
            Thread.Sleep(0);
        }

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
        t.Join();
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
        Console.ReadLine();
    }
}


Visual C++

// [C++]
// Compile using /clr option.
using namespace System;
using namespace System::Threading;

// Simple threading scenario:  Start a Shared method running
// on a second thread.
public ref class ThreadExample
{
public:

   // The ThreadProc method is called when the thread starts.
   // It loops ten times, writing to the console and yielding 
   // the rest of its time slice each time, and then ends.
   static void ThreadProc()
   {
      for ( int i = 0; i < 10; i++ )
      {
         Console::Write(  "ThreadProc: " );
         Console::WriteLine( i );

         // Yield the rest of the time slice.
         Thread::Sleep( 0 );

      }
   }

};

int main()
{
   Console::WriteLine( "Main thread: Start a second thread." );

   // Create the thread, passing a ThreadStart delegate that
   // represents the ThreadExample::ThreadProc method.  For a 
   // delegate representing a static method, no object is
   // required.
   Thread^ oThread = gcnew Thread( gcnew ThreadStart( &ThreadExample::ThreadProc ) );

   // Start ThreadProc.  Note that on a uniprocessor, the new 
   // thread does not get any processor time until the main thread 
   // is preempted or yields.  Uncomment the Thread::Sleep that 
   // follows oThread->Start() to see the difference.
   oThread->Start();

   //Thread::Sleep(0);
   for ( int i = 0; i < 4; i++ )
   {
      Console::WriteLine(  "Main thread: Do some work." );
      Thread::Sleep( 0 );

   }
   Console::WriteLine(  "Main thread: Call Join(), to wait until ThreadProc ends." );
   oThread->Join();
   Console::WriteLine(  "Main thread: ThreadProc.Join has returned.  Press Enter to end program." );
   Console::ReadLine();
   return 0;
}



This code produces output similar to the following:

 [VB, C++, C#]
 Main thread: Start a second thread.
 Main thread: Do some work.
 ThreadProc: 0
 Main thread: Do some work.
 ThreadProc: 1
 Main thread: Do some work.
 ThreadProc: 2
 Main thread: Do some work.
 ThreadProc: 3
 Main thread: Call Join(), to wait until ThreadProc ends.
 ThreadProc: 4
 ThreadProc: 5
 ThreadProc: 6
 ThreadProc: 7
 ThreadProc: 8
 ThreadProc: 9
 Main thread: ThreadProc.Join has returned.  Press Enter to end program.
Version Information

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, 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.
Thread Safety

This type is thread safe.

See Also

Reference

Other Resources