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 ref class Thread sealed : CriticalFinalizerObject, _Thread

NameDescription
System_CAPS_pubmethodThread(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.

System_CAPS_pubmethodThread(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.

System_CAPS_pubmethodThread(ThreadStart^)

Initializes a new instance of the Thread class.

System_CAPS_pubmethodThread(ThreadStart^, Int32)

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

NameDescription
System_CAPS_pubpropertyApartmentState

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

System_CAPS_pubpropertySystem_CAPS_staticCurrentContext

Gets the current context in which the thread is executing.

System_CAPS_pubpropertyCurrentCulture

Gets or sets the culture for the current thread.

System_CAPS_pubpropertySystem_CAPS_staticCurrentPrincipal

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

System_CAPS_pubpropertySystem_CAPS_staticCurrentThread

Gets the currently running thread.

System_CAPS_pubpropertyCurrentUICulture

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

System_CAPS_pubpropertyExecutionContext

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

System_CAPS_pubpropertyIsAlive

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

System_CAPS_pubpropertyIsBackground

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

System_CAPS_pubpropertyIsThreadPoolThread

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

System_CAPS_pubpropertyManagedThreadId

Gets a unique identifier for the current managed thread.

System_CAPS_pubpropertyName

Gets or sets the name of the thread.

System_CAPS_pubpropertyPriority

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

System_CAPS_pubpropertyThreadState

Gets a value containing the states of the current thread.

NameDescription
System_CAPS_pubmethodAbort()

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_pubmethodAbort(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.

System_CAPS_pubmethodSystem_CAPS_staticAllocateDataSlot()

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

System_CAPS_pubmethodSystem_CAPS_staticAllocateNamedDataSlot(String^)

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

System_CAPS_pubmethodSystem_CAPS_staticBeginCriticalRegion()

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_pubmethodSystem_CAPS_staticBeginThreadAffinity()

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_pubmethodDisableComObjectEagerCleanup()

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

System_CAPS_pubmethodSystem_CAPS_staticEndCriticalRegion()

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_pubmethodSystem_CAPS_staticEndThreadAffinity()

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

System_CAPS_pubmethodEquals(Object^)

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

System_CAPS_protmethodFinalize()

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

System_CAPS_pubmethodSystem_CAPS_staticFreeNamedDataSlot(String^)

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_pubmethodGetApartmentState()

Returns an ApartmentState value indicating the apartment state.

System_CAPS_pubmethodGetCompressedStack()

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

System_CAPS_pubmethodSystem_CAPS_staticGetData(LocalDataStoreSlot^)

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_pubmethodSystem_CAPS_staticGetDomain()

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

System_CAPS_pubmethodSystem_CAPS_staticGetDomainID()

Returns a unique application domain identifier.

System_CAPS_pubmethodGetHashCode()

Returns a hash code for the current thread.(Overrides Object::GetHashCode().)

System_CAPS_pubmethodSystem_CAPS_staticGetNamedDataSlot(String^)

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

System_CAPS_pubmethodGetType()

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

System_CAPS_pubmethodInterrupt()

Interrupts a thread that is in the WaitSleepJoin thread state.

System_CAPS_pubmethodJoin()

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

System_CAPS_pubmethodJoin(Int32)

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_pubmethodJoin(TimeSpan)

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_pubmethodSystem_CAPS_staticMemoryBarrier()

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_pubmethodSystem_CAPS_staticResetAbort()

Cancels an Abort requested for the current thread.

System_CAPS_pubmethodResume()

Obsolete.Resumes a thread that has been suspended.

System_CAPS_pubmethodSetApartmentState(ApartmentState)

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

System_CAPS_pubmethodSetCompressedStack(CompressedStack^)

Obsolete.Applies a captured CompressedStack to the current thread.

System_CAPS_pubmethodSystem_CAPS_staticSetData(LocalDataStoreSlot^, Object^)

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_pubmethodSystem_CAPS_staticSleep(Int32)

Suspends the current thread for the specified number of milliseconds.

System_CAPS_pubmethodSystem_CAPS_staticSleep(TimeSpan)

Suspends the current thread for the specified amount of time.

System_CAPS_pubmethodSystem_CAPS_staticSpinWait(Int32)

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

System_CAPS_pubmethodStart()

Causes the operating system to change the state of the current instance to ThreadState::Running.

System_CAPS_pubmethodStart(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.

System_CAPS_pubmethodSuspend()

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

System_CAPS_pubmethodToString()

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

System_CAPS_pubmethodTrySetApartmentState(ApartmentState)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileRead(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.

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(Byte%, Byte)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(Double%, Double)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(Int16%, Int16)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(Int32%, Int32)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(Int64%, Int64)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(IntPtr%, IntPtr)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(Object^%, Object^)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(SByte%, SByte)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(Single%, Single)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(UInt16%, UInt16)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(UInt32%, UInt32)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(UInt64%, UInt64)

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

System_CAPS_pubmethodSystem_CAPS_staticVolatileWrite(UIntPtr%, UIntPtr)

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

System_CAPS_pubmethodSystem_CAPS_staticYield()

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_pubinterfaceSystem_CAPS_privmethod_Thread::GetIDsOfNames(Guid%, IntPtr, UInt32, UInt32, IntPtr)

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

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Thread::GetTypeInfo(UInt32, UInt32, IntPtr)

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

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Thread::GetTypeInfoCount(UInt32%)

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

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Thread::Invoke(UInt32, Guid%, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

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:

    No code example is currently available or this language may not be supported.

    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.

    No code example is currently available or this language may not be supported.
  • If the method has an argument, you pass a ParameterizedThreadStart delegate to the constructor. It has the signature:

    No code example is currently available or this language may not be supported.

    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(ParameterizedThreadStart^) constructor. This version of the ExecuteInForeground method has a single parameter that represents the approximate number of milliseconds the loop is to execute.

    No code example is currently available or this language may not be supported.

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) CurrentThread property to retrieve a reference to the currently executing thread from the code that the thread is executing. The following example uses the CurrentThread property to display information about the main application thread, another foreground thread, a background thread, and a thread pool thread.

No code example is currently available or this language may not be supported.

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<TResult> 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 IsBackground 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.

No code example is currently available or this language may not be supported.

Each thread has a culture, represented by the CurrentCulture property, and a UI culture, represented by the CurrentUICulture 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(ParameterizedThreadStart^) 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:

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. 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 ManagedThreadId 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 IsThreadPoolThread property, which indicates whether a thread is a thread pool thread.

  • The IsBackground 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.

// [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
Show: