Udostępnij za pośrednictwem


Thread Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Creates and controls a thread, and gets its status.

Inheritance Hierarchy

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

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

Syntax

'Declaration
<ComVisibleAttribute(True)> _
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
Public NotInheritable Class Thread _
    Inherits CriticalFinalizerObject
[ComVisibleAttribute(true)]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
public sealed class Thread : CriticalFinalizerObject

The Thread type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Thread(ThreadStart) Initializes a new instance of the Thread class.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 CurrentCulture Gets or sets the culture for the current thread.
Public propertyStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CurrentThread Gets the currently running thread.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 IsAlive Gets a value that indicates the execution status of the current thread.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 IsBackground Gets or sets a value that indicates whether a thread is a background thread.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 ManagedThreadId Gets a unique identifier for the current, managed thread.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Name Gets or sets the name of the thread.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 ThreadState Gets a value that contains the states of the current thread.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Abort Security Critical. 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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Releases all the resources used by the CriticalFinalizerObject class. (Inherited from CriticalFinalizerObject.)

In Silverlight for Windows Phone Windows Phone OS 7.1, this member is inherited from Object.Finalize().

In XNA Framework Xbox 360, this member is inherited from Object.Finalize().
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetDomain Returns the current domain in which the current thread is running.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Returns a hash code for the current thread. (Overrides Object.GetHashCode().)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Join() Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Join(Int32) Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemoryBarrier Ensures that memory accesses that appear before the call to MemoryBarrier, in program order, will not execute after the call to MemoryBarrier, and that memory accesses that appear after the call to MemoryBarrier will not execute before that call.
Public methodSupported by Xbox 360 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 methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 Sleep(Int32) Suspends the current thread for a specified time.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 Sleep(TimeSpan) Blocks the current thread for a specified time.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 SpinWait Causes a thread to wait the number of times defined by the iterations parameter.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Start() Causes the operating system to change the state of the current instance to ThreadState.Running.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 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 that the thread executes.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Remarks

A process can create one or more threads to execute portions of the program code associated with the process. The unit of execution for managed threads is the method. Use a ThreadStart delegate or the ParameterizedThreadStart delegate to specify the method executed by a thread. The ParameterizedThreadStart delegate allows you to pass data to the thread procedure as a parameter.

For the duration of its existence, a thread is always in one or more of the states defined by ThreadState.

The ManagedThreadId property 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.

NoteNote:

An operating-system thread ID has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged 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.

It is not necessary to create threads yourself. The BackgroundWorker and ThreadPool classes enable you to use system-managed background threads in a simple, task-oriented way. For background tasks that return results to the user interface (UI) thread, the simplest programming technique is to use the BackgroundWorker class. The following table lists some sources of information on various kinds of concurrent programming.

Task

See

Execute a background task that communicates with the main application thread by using events.

BackgroundWorker

Execute a background task that has little or no need to communicate with the main application thread.

The Managed Thread Pool

Protect regions of code or fields from concurrent access.

Monitor; the Visual Basic SyncLock statement (lock statement in C#)

Synchronize the activities of multiple threads.

EventWaitHandle, AutoResetEvent, and ManualResetEvent

Execute code in the background at regular intervals.

Timer

Execute code on the UI thread at regular intervals.

DispatcherTimer

Provide lock-free concurrent access to data.

Interlocked Operations

Create your own threads.

Thread class; Creating Threads and Passing Data at Start Time

Examples

This section contains two examples. The first example shows how to create a thread that executes a static method. The second example shows how to create a thread that executes an instance method.

The examples display their output in a TextBlock on the UI thread. To access the TextBlock from the callback thread, the examples use the Dispatcher property to obtain a Dispatcher object for the TextBlock, and then use the Dispatcher.BeginInvoke method to make the cross-thread call.

For more examples of thread creation, see Creating Threads and Passing Data at Start Time. For examples of coordinating the actions of threads with wait handles, see EventWaitHandle. For examples of coordinating the actions of threads with critical sections (lock in C#, SyncLock in Visual Basic), see Monitor. For examples of how to use thread pool threads, see BackgroundWorker, ThreadPool, and Timer.

Example 1

The following example shows how to create a thread that executes a static method.

Imports System.Threading

Public Class Example

   Private Shared outputBlock As System.Windows.Controls.TextBlock

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      Example.outputBlock = outputBlock

      ' To start a thread using a static thread procedure, use the
      ' class name and method name when you create the ThreadStart
      ' delegate. Visual Basic expands the AddressOf expression 
      ' to the appropriate delegate creation syntax:
      '    New ThreadStart(AddressOf Example.DoWork)
      '
      Dim newThread As New Thread(AddressOf Example.DoWork)
      newThread.Start()

   End Sub

   ' Simulate work. To communicate with objects on the UI thread, get the 
   ' Dispatcher for one of the UI objects. Use the Dispatcher object's 
   ' BeginInvoke method to queue a delegate that will run on the UI thread,
   ' and therefore can safely access UI elements like the TextBlock.
   Private Shared Sub DoWork()
      Dim display As New Action(Of String)(AddressOf DisplayOutput)

      outputBlock.Dispatcher.BeginInvoke(display, _
         "Hello from a Shared thread procedure." & vbCrLf)
   End Sub

   ' The Dispatcher.BeginInvoke method runs this helper method on the 
   ' UI thread, so it can safely access the TextBlock that is used to 
   ' display the output.
   Private Shared Sub DisplayOutput(msg)
      outputBlock.Text &= msg
   End Sub

End Class

' This code example produces the following output:
'
'Hello from a Shared thread procedure.
using System;
using System.Threading;

public class Example
{
   private static System.Windows.Controls.TextBlock outputBlock;

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      Example.outputBlock = outputBlock;

      // To start a thread using a static thread procedure, use the
      // class name and method name when you create the ThreadStart
      // delegate. C# expands the method name to the appropriate 
      // delegate creation syntax:
      //    New ThreadStart(Example.DoWork)
      //
      Thread newThread = new Thread(Example.DoWork);
      newThread.Start();
   }

   // Simulate work. To communicate with objects on the UI thread, get the 
   // Dispatcher for one of the UI objects. Use the Dispatcher object's 
   // BeginInvoke method to queue a delegate that will run on the UI thread,
   // and therefore can safely access UI elements like the TextBlock.
   private static void DoWork()
   {
      outputBlock.Dispatcher.BeginInvoke(delegate () { 
         outputBlock.Text += "Hello from a static thread procedure.\n"; 
      });
   }
}

/* This code example produces the following output:

Hello from a static thread procedure.
 */

Example 2

The following example shows how to create a thread that executes an instance method.

Imports System.Threading

Public Class Example

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      ' To start a thread using an instance method for the thread 
      ' procedure, use the instance variable and method name when 
      ' you create the ThreadStart delegate. Visual Basic expands 
      ' the AddressOf expression to the appropriate delegate 
      ' creation syntax:
      '    New ThreadStart(AddressOf w.DoMoreWork)
      '
      Dim w As New Work()
      w.Data = 42
      w.Output = outputBlock

      Dim newThread As Thread = New Thread(AddressOf w.DoMoreWork)
      newThread.Start()
   End Sub

End Class

Public Class Work
   Public Data As Integer
   Public Output As System.Windows.Controls.TextBlock

   ' Simulate work. To communicate with objects on the UI thread, get the 
   ' Dispatcher for one of the UI objects. Use the Dispatcher object's 
   ' BeginInvoke method to queue a delegate that will run on the UI thread,
   ' and therefore can safely access UI elements like the TextBlock.
   Public Sub DoMoreWork()
      Dim display As New Action(Of String)(AddressOf DisplayOutput)

      Output.Dispatcher.BeginInvoke(display, _
         String.Format("Instance thread procedure. Data={0}", Data) & vbCrLf)
   End Sub

   ' The Dispatcher.BeginInvoke method runs this helper method on the 
   ' UI thread, so it can safely access the TextBlock that is used to 
   ' display the output.
   Private Sub DisplayOutput(msg)
      Output.Text &= msg
   End Sub

End Class

' This code example produces the following output:
'
'Instance thread procedure. Data=42
using System;
using System.Threading;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // To start a thread using an instance method for the thread 
      // procedure, use the instance variable and method name when 
      // you create the ThreadStart delegate. C# expands the object
      // reference and method name to the appropriate delegate 
      // creation syntax:
      //    New ThreadStart(AddressOf w.DoMoreWork)
      //
      Work w = new Work();
      w.Data = 42;
      w.Output = outputBlock;

      Thread newThread = new Thread(w.DoMoreWork);
      newThread.Start();
   }
}

public class Work
{
   public int Data;
   public System.Windows.Controls.TextBlock Output;

   // Simulate work. To communicate with objects on the UI thread, get the 
   // Dispatcher for one of the UI objects. Use the Dispatcher object's 
   // BeginInvoke method to queue a delegate that will run on the UI thread,
   // and therefore can safely access UI elements like the TextBlock.
   public void DoMoreWork()
   {
      Output.Dispatcher.BeginInvoke(delegate () {
         Output.Text += String.Format("Instance thread procedure. Data={0}\n", Data);
      });
   }
}

// This code example produces the following output:
//
//Instance thread procedure. Data=42

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

This type is thread safe.