Thread Class
 

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

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


[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
public sealed class Thread : CriticalFinalizerObject, _Thread
[ClassInterfaceAttribute(ClassInterfaceType::None)]
[ComVisibleAttribute(true)]
public ref class Thread sealed : CriticalFinalizerObject, _Thread
[<Sealed>]
[<ClassInterfaceAttribute(ClassInterfaceType.None)>]
[<ComVisibleAttribute(true)>]
type Thread = 
    class
        inherit CriticalFinalizerObject
        interface _Thread
    end
<ClassInterfaceAttribute(ClassInterfaceType.None)>
<ComVisibleAttribute(True)>
Public NotInheritable Class Thread
	Inherits CriticalFinalizerObject
	Implements _Thread
NameDescription
System_CAPS_pubmethod Thread

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.

System_CAPS_pubmethod Thread

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.

System_CAPS_pubmethod Thread

Initializes a new instance of the Thread class.

System_CAPS_pubmethod Thread

Initializes a new instance of the Thread class, specifying the maximum stack size for the thread.

NameDescription
System_CAPS_pubproperty

Obsolete. Gets or sets the apartment state of this thread.

System_CAPS_pubproperty System_CAPS_static

Gets the current context in which the thread is executing.

System_CAPS_pubproperty

Gets or sets the culture for the current thread.

System_CAPS_pubproperty System_CAPS_static

Gets or sets the thread's current principal (for role-based security).

System_CAPS_pubproperty System_CAPS_static

Gets the currently running thread.

System_CAPS_pubproperty

Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.

System_CAPS_pubproperty

Gets an ExecutionContext object that contains information about the various contexts of the current thread.

System_CAPS_pubproperty

Gets a value indicating the execution status of the current thread.

System_CAPS_pubproperty

Gets or sets a value indicating whether or not a thread is a background thread.

System_CAPS_pubproperty

Gets a value indicating whether or not a thread belongs to the managed thread pool.

System_CAPS_pubproperty

Gets a unique identifier for the current managed thread.

System_CAPS_pubproperty

Gets or sets the name of the thread.

System_CAPS_pubproperty

Gets or sets a value indicating the scheduling priority of a thread.

System_CAPS_pubproperty

Gets a value containing the states of the current thread.

NameDescription
System_CAPS_pubmethod 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.

System_CAPS_pubmethod Abort

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.

System_CAPS_pubmethod System_CAPS_static AllocateDataSlot

Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

System_CAPS_pubmethod System_CAPS_static AllocateNamedDataSlot

Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

System_CAPS_pubmethod System_CAPS_static 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.

System_CAPS_pubmethod System_CAPS_static BeginThreadAffinity

Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.

System_CAPS_pubmethod DisableComObjectEagerCleanup

Turns off automatic cleanup of runtime callable wrappers (RCW) for the current thread.

System_CAPS_pubmethod System_CAPS_static 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.

System_CAPS_pubmethod System_CAPS_static EndThreadAffinity

Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.

System_CAPS_pubmethod Equals

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethod Finalize

Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object. (Overrides CriticalFinalizerObjectFinalize.)

System_CAPS_pubmethod System_CAPS_static 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.

System_CAPS_pubmethod GetApartmentState

Returns an ApartmentState value indicating the apartment state.

System_CAPS_pubmethod GetCompressedStack

Obsolete. Returns a CompressedStack object that can be used to capture the stack for the current thread.

System_CAPS_pubmethod System_CAPS_static 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.

System_CAPS_pubmethod System_CAPS_static GetDomain

Returns the current domain in which the current thread is running.

System_CAPS_pubmethod System_CAPS_static GetDomainID

Returns a unique application domain identifier.

System_CAPS_pubmethod GetHashCode

Returns a hash code for the current thread.(Overrides ObjectGetHashCode.)

System_CAPS_pubmethod System_CAPS_static GetNamedDataSlot

Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

System_CAPS_pubmethod GetType

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethod Interrupt

Interrupts a thread that is in the WaitSleepJoin thread state.

System_CAPS_pubmethod Join

Blocks the calling thread until the thread represented by this instance terminates, while continuing to perform standard COM and SendMessage pumping.

System_CAPS_pubmethod Join

Blocks the calling thread until the thread represented by this instance terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.

System_CAPS_pubmethod Join

Blocks the calling thread until the thread represented by this instance terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.

System_CAPS_pubmethod System_CAPS_static 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.

System_CAPS_pubmethod System_CAPS_static ResetAbort

Cancels an Abort requested for the current thread.

System_CAPS_pubmethod Resume

Obsolete. Resumes a thread that has been suspended.

System_CAPS_pubmethod SetApartmentState

Sets the apartment state of a thread before it is started.

System_CAPS_pubmethod SetCompressedStack

Obsolete. Applies a captured CompressedStack to the current thread.

System_CAPS_pubmethod System_CAPS_static 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.

System_CAPS_pubmethod System_CAPS_static Sleep

Suspends the current thread for the specified number of milliseconds.

System_CAPS_pubmethod System_CAPS_static Sleep

Suspends the current thread for the specified amount of time.

System_CAPS_pubmethod System_CAPS_static SpinWait

Causes a thread to wait the number of times defined by the iterations parameter.

System_CAPS_pubmethod Start

Causes the operating system to change the state of the current instance to ThreadStateRunning.

System_CAPS_pubmethod Start

Causes the operating system to change the state of the current instance to ThreadStateRunning, and optionally supplies an object containing data to be used by the method the thread executes.

System_CAPS_pubmethod Suspend

Obsolete. Either suspends the thread, or if the thread is already suspended, has no effect.

System_CAPS_pubmethod ToString

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_pubmethod TrySetApartmentState

Sets the apartment state of a thread before it is started.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileRead

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.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static VolatileWrite

Writes a value to a field immediately, so that the value is visible to all processors in the computer.

System_CAPS_pubmethod System_CAPS_static 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.

NameDescription
System_CAPS_pubinterface System_CAPS_privmethod _ThreadGetIDsOfNames

Maps a set of names to a corresponding set of dispatch identifiers.

System_CAPS_pubinterface System_CAPS_privmethod _ThreadGetTypeInfo

Retrieves the type information for an object, which can then be used to get the type information for an interface.

System_CAPS_pubinterface System_CAPS_privmethod _ThreadGetTypeInfoCount

Retrieves the number of type information interfaces that an object provides (either 0 or 1).

System_CAPS_pubinterface System_CAPS_privmethod _ThreadInvoke

Provides access to properties and methods exposed by an object.

When a process starts, the common language runtime automatically creates a single foreground thread to execute application code. Along with this main foreground thread, a process can create one or more threads to execute a portion of the program code associated with the process. These threads can execute either in the foreground or in the background. In addition, you can use the ThreadPool class to execute code on worker threads that are managed by the common language runtime.

In this section

Starting a thread
Retrieving Thread objects
Foreground and background threads
Culture and threads
Getting information about and controlling threads
Accessing the source code for the Thread class

You start a thread by supplying a delegate that represents the method the thread is to execute in its class constructor. You then call the Start method to begin execution.

The Thread constructors can take either of two delegate types, depending on whether you can pass an argument to the method to be executed:

  • If the method has no arguments, you pass a ThreadStart delegate to the constructor. It has the signature:

    public delegate void ThreadStart()
    Public Delegate Sub ThreadStart()

    The following example creates and starts a thread that executes the ExecuteInForeground method. The method displays information about some thread properties, then executes a loop in which it pauses for half a second and displays the elapsed number of seconds. When the thread has executed for at least five seconds, the loop ends and the thread terminates execution.

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    public class Example
    {
       public static void Main()
       {
          var th = new Thread(ExecuteInForeground);
          th.Start();
          Thread.Sleep(1000);
          Console.WriteLine("Main thread ({0}) exiting...", 
                            Thread.CurrentThread.ManagedThreadId); 
       }
    
       private static void ExecuteInForeground()
       {
          DateTime start = DateTime.Now;
          var sw = Stopwatch.StartNew();
          Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority);
          do { 
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000.0);
             Thread.Sleep(500);
          } while (sw.ElapsedMilliseconds <= 5000);
          sw.Stop(); 
       }
    }
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.51 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.02 seconds
    //       Thread 3: Elapsed 1.53 seconds
    //       Thread 3: Elapsed 2.05 seconds
    //       Thread 3: Elapsed 2.55 seconds
    //       Thread 3: Elapsed 3.07 seconds
    //       Thread 3: Elapsed 3.57 seconds
    //       Thread 3: Elapsed 4.07 seconds
    //       Thread 3: Elapsed 4.58 seconds
    Imports System.Diagnostics
    Imports System.Threading
    
    Module Example
       Public Sub Main()
          Dim th As New Thread(AddressOf ExecuteInForeground)
          th.Start()
          Thread.Sleep(1000)
          Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId) 
       End Sub
    
       Private Sub ExecuteInForeground()
          Dim start As DateTime = DateTime.Now
          Dim sw As Stopwatch = Stopwatch.StartNew()
          Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority)
          Do 
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000)
             Thread.Sleep(500)
          Loop While sw.ElapsedMilliseconds <= 5000
          sw.Stop() 
       End Sub
    End Module
    ' The example displays output like the following:
    '       Thread 3: Running, Priority Normal
    '       Thread 3: Elapsed 0.00 seconds
    '       Thread 3: Elapsed 0.51 seconds
    '       Main thread (1) exiting...
    '       Thread 3: Elapsed 1.02 seconds
    '       Thread 3: Elapsed 1.53 seconds
    '       Thread 3: Elapsed 2.05 seconds
    '       Thread 3: Elapsed 2.55 seconds
    '       Thread 3: Elapsed 3.07 seconds
    '       Thread 3: Elapsed 3.57 seconds
    '       Thread 3: Elapsed 4.07 seconds
    '       Thread 3: Elapsed 4.58 seconds
  • If the method has an argument, you pass a ParameterizedThreadStart delegate to the constructor. It has the signature:

    public delegate void ParameterizedThreadStart(object obj)
    Public Delegate Sub ParameterizedThreadStart(obj As Object)

    The method executed by the delegate can then cast (in C#) or convert (in Visual Basic) the parameter to the appropriate type.

    The following example is identical to the previous one, except that it calls the Thread constructor. This version of the ExecuteInForeground method has a single parameter that represents the approximate number of milliseconds the loop is to execute.

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    public class Example
    {
       public static void Main()
       {
          var th = new Thread(ExecuteInForeground);
          th.Start(4500);
          Thread.Sleep(1000);
          Console.WriteLine("Main thread ({0}) exiting...", 
                            Thread.CurrentThread.ManagedThreadId); 
       }
    
       private static void ExecuteInForeground(Object obj)
       {
          int interval;
          try {
             interval = (int) obj;
          }
          catch (InvalidCastException) {
             interval = 5000;
          }
          DateTime start = DateTime.Now;
          var sw = Stopwatch.StartNew();
          Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority);
          do { 
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000.0);
             Thread.Sleep(500);
          } while (sw.ElapsedMilliseconds <= interval);
          sw.Stop(); 
       }
    }
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.52 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.03 seconds
    //       Thread 3: Elapsed 1.55 seconds
    //       Thread 3: Elapsed 2.06 seconds
    //       Thread 3: Elapsed 2.58 seconds
    //       Thread 3: Elapsed 3.09 seconds
    //       Thread 3: Elapsed 3.61 seconds
    //       Thread 3: Elapsed 4.12 seconds
    Imports System.Diagnostics
    Imports System.Threading
    
    Module Example
       Public Sub Main()
          Dim th As New Thread(AddressOf ExecuteInForeground)
          th.Start(4500)
          Thread.Sleep(1000)
          Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId) 
       End Sub
    
       Private Sub ExecuteInForeground(obj As Object)
          Dim interval As Integer
          If IsNumeric(obj) Then
             interval = CInt(obj)
          Else
             interval = 5000
          End If   
          Dim start As DateTime = DateTime.Now
          Dim sw As Stopwatch = Stopwatch.StartNew()
          Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority)
          Do 
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000)
             Thread.Sleep(500)
          Loop While sw.ElapsedMilliseconds <= interval
          sw.Stop() 
       End Sub
    End Module
    ' The example displays output like the following:
    '       Thread 3: Running, Priority Normal
    '       Thread 3: Elapsed 0.00 seconds
    '       Thread 3: Elapsed 0.52 seconds
    '       Main thread (1) exiting...
    '       Thread 3: Elapsed 1.03 seconds
    '       Thread 3: Elapsed 1.55 seconds
    '       Thread 3: Elapsed 2.06 seconds
    '       Thread 3: Elapsed 2.58 seconds
    '       Thread 3: Elapsed 3.09 seconds
    '       Thread 3: Elapsed 3.61 seconds
    '       Thread 3: Elapsed 4.12 seconds

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.

You can use the static (Shared in Visual Basic) property to retrieve a reference to the currently executing thread from the code that the thread is executing. The following example uses the property to display information about the main application thread, another foreground thread, a background thread, and a thread pool thread.

using System;
using System.Threading;

public class Example
{
   static Object obj = new Object();

   public static void Main()
   {
      ThreadPool.QueueUserWorkItem(ShowThreadInformation);
      var th1 = new Thread(ShowThreadInformation);
      th1.Start();
      var th2 = new Thread(ShowThreadInformation);
      th2.IsBackground = true;
      th2.Start();
      Thread.Sleep(500);
      ShowThreadInformation(null); 
   }

   private static void ShowThreadInformation(Object state)
   {
      lock (obj) {
         var th  = Thread.CurrentThread;
         Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId);
         Console.WriteLine("   Background thread: {0}", th.IsBackground);
         Console.WriteLine("   Thread pool thread: {0}", th.IsThreadPoolThread);
         Console.WriteLine("   Priority: {0}", th.Priority);
         Console.WriteLine("   Culture: {0}", th.CurrentCulture.Name);
         Console.WriteLine("   UI culture: {0}", th.CurrentUICulture.Name);
         Console.WriteLine();
      }   
   }
}
// The example displays output like the following:
//       Managed thread #6:
//          Background thread: True
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #3:
//          Background thread: True
//          Thread pool thread: True
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #4:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #1:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
Imports System.Threading

Module Example
   Private lock As New Object()

   Public Sub Main()
      ThreadPool.QueueUserWorkItem(AddressOf ShowThreadInformation)
      Dim th1 As New Thread(AddressOf ShowThreadInformation)
      th1.Start()
      Dim th2 As New Thread(AddressOf ShowThreadInformation)
      th2.IsBackground = True
      th2.Start()
      Thread.Sleep(500)
      ShowThreadInformation(Nothing) 
   End Sub

   Private Sub ShowThreadInformation(state As Object)
      SyncLock lock
         Dim th As Thread = Thread.CurrentThread
         Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId)
         Console.WriteLine("   Background thread: {0}", th.IsBackground)
         Console.WriteLine("   Thread pool thread: {0}", th.IsThreadPoolThread)
         Console.WriteLine("   Priority: {0}", th.Priority)
         Console.WriteLine("   Culture: {0}", th.CurrentCulture.Name)
         Console.WriteLine("   UI culture: {0}", th.CurrentUICulture.Name)
         Console.WriteLine()
      End SyncLock
   End Sub
End Module
' The example displays output like the following:
'       ' Managed thread #6:
'          Background thread: True
'          Thread pool thread: False
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US
'       
'       Managed thread #3:
'          Background thread: True
'          Thread pool thread: True
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US
'       
'       Managed thread #4:
'          Background thread: False
'          Thread pool thread: False
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US
'       
'       Managed thread #1:
'          Background thread: False
'          Thread pool thread: False
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US

Instances of the Thread class represent either foreground threads or background threads. Background threads are identical to foreground threads with one exception: a background thread does not keep a process running if all foreground threads have terminated. Once all foreground threads have been stopped, the runtime stops all background threads and shuts down.

By default, the following threads execute in the foreground:

  • The main application thread.

  • All threads created by calling a Thread class constructor.

The following threads execute in the background by default:

  • Thread pool threads, which are a pool of worker threads maintained by the runtime. You can configure the thread pool and schedule work on thread pool threads by using the ThreadPool class.

    System_CAPS_noteNote

    Task-based asynchronous operations automatically execute on thread pool threads. Task-based asynchronous operations use the Task and Task classes to implement the task-based asynchronous pattern.

  • All threads that enter the managed execution environment from unmanaged code.

You can change a thread to execute in the background by setting the property at any time. Background threads are useful for any operation that should continue as long as an application is running but should not prevent the application from terminating, such as monitoring file system changes or incoming socket connections.

The following example illustrates the difference between foreground and background threads. It is like the first example in the Starting a thread section, except that it sets the thread to execute in the background before starting it. As the output shows, the loop is interrupted before it executes for five seconds.

using System;
using System.Diagnostics;
using System.Threading;

public class Example
{
   public static void Main()
   {
      var th = new Thread(ExecuteInForeground);
      th.IsBackground = true;
      th.Start();
      Thread.Sleep(1000);
      Console.WriteLine("Main thread ({0}) exiting...", 
                        Thread.CurrentThread.ManagedThreadId); 
   }

   private static void ExecuteInForeground()
   {
      DateTime start = DateTime.Now;
      var sw = Stopwatch.StartNew();
      Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority);
      do { 
         Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000.0);
         Thread.Sleep(500);
      } while (sw.ElapsedMilliseconds <= 5000);
      sw.Stop(); 
   }
}
// The example displays output like the following:
//       Thread 3: Background, Priority Normal
//       Thread 3: Elapsed 0.00 seconds
//       Thread 3: Elapsed 0.51 seconds
//       Main thread (1) exiting...
Imports System.Diagnostics
Imports System.Threading

Module Example
   Public Sub Main()
      Dim th As New Thread(AddressOf ExecuteInForeground)
      th.IsBackground = True
      th.Start()
      Thread.Sleep(1000)
      Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId) 
   End Sub

   Private Sub ExecuteInForeground()
      Dim start As DateTime = DateTime.Now
      Dim sw As Stopwatch = Stopwatch.StartNew()
      Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority)
      Do 
         Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000)
         Thread.Sleep(500)
      Loop While sw.ElapsedMilliseconds <= 5000
      sw.Stop() 
   End Sub
End Module
' The example displays output like the following:
'       Thread 3: Background, Priority Normal
'       Thread 3: Elapsed 0.00 seconds
'       Thread 3: Elapsed 0.51 seconds
'       Main thread (1) exiting...

Each thread has a culture, represented by the property, and a UI culture, represented by the property. The current culture supports such culture-sensitive operations as parsing and formatting, string comparison and sorting, and also controls the writing system and calendar used by a thread. The current UI culture provides for culture-sensitive retrieval of resources in resource files.

When a new thread is instantiated, its culture and UI culture are defined by the current system culture and UI culture, and not by the culture and UI culture of the thread from which the new thread is created. This means, for example, that if the current system culture is English (United States) and the current culture of the primary application thread is French (France), the culture of a new thread created by calling the Thread constructor from the primary thread is English (United States), and not French (France). For more information, see the "Culture and threads" section of the CultureInfo class topic.

System_CAPS_importantImportant

This is not true of threads that execute asynchronous operations for apps that target the .NET Framework 4.6 and later versions, In this case, the culture and UI culture is part of an asynchronous operations' context; the thread on which an asynchronous operation executes by default inherits the culture and UI culture of the thread from which the asynchronous operation was launched. For more information, see the "Culture and task-based asynchronous operations" section of the CultureInfo class topic.

You can do either of the following to ensure that all of the threads executing in an application share the same culture and UI culture:

  • You can pass a CultureInfo object that represents that culture to the ParameterizedThreadStart delegate or the ThreadPoolQueueUserWorkItem method.

  • For apps running on the .NET Framework 4.5 and later versions, you can define the culture and UI culture that is to be assigned to all threads created in an application domain by setting the value of the and properties. Note that this is a per-application domain setting.

For more information and examples, see the "Culture and threads" section of the CultureInfo class topic.

You can retrieve a number of property values that provide information about a thread. In some cases, you can also set these property values to control the operation of the thread. These thread properties include:

  • A name. is a write-once property that you can use to identify a thread. Its default value is null.

  • A hash code, which you can retrieve by calling the GetHashCode method. The hash code can be used to uniquely identify a thread; for the lifetime of your thread, its hash code will not collide with the value from any other thread, regardless of the application domain from which you obtain the value.

  • A thread ID. The value of the read-only property is assigned by the runtime and uniquely identifies a thread within its process.

    System_CAPS_noteNote

    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.

  • The thread's current state. For the duration of its existence, a thread is always in one or more of the states defined by the ThreadState property.

  • A scheduling priority level, which is defined by the ThreadPriority property. Although you can set this value to request a thread's priority, it is not guaranteed to be honored by the operating system.

  • The read-only property, which indicates whether a thread is a thread pool thread.

  • The property. For more information, see the Foreground and background threads section.

To view the .NET Framework source code for the Thread class, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

The following example demonstrates simple threading functionality.

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();
    }
}
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++]
// 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.
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0

This type is thread safe.

Return to top