Dieser Artikel wurde maschinell übersetzt. Wenn Sie die englische Version des Artikels anzeigen möchten, aktivieren Sie das Kontrollkästchen Englisch. Sie können den englischen Text auch in einem Popupfenster anzeigen, indem Sie den Mauszeiger über den Text bewegen.
Veröffentlicht: Oktober 2016
Assembly: mscorlib (in mscorlib.dll)
|_Thread.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)|
|_Thread.GetTypeInfo(UInt32, UInt32, IntPtr)|
|_Thread.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)|
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 T:System.Threading.ThreadPool class to execute code on worker threads that are managed by the common language runtime.
In this section
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 M:System.Threading.Thread.Start method to begin execution.
The T:System.Threading.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 T:System.Threading.ThreadStart delegate to the constructor. It has the signature:
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.
If the method has an argument, you pass a T:System.Threading.ParameterizedThreadStart delegate to the constructor. It has the signature:
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 M:System.Threading.Thread.#ctor(System.Threading.ParameterizedThreadStart) constructor. This version of the ExecuteInForeground method has a single parameter that represents the approximate number of milliseconds the loop is to execute.
It is not necessary to retain a reference to a T:System.Threading.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) P:System.Threading.Thread.CurrentThread property to retrieve a reference to the currently executing thread from the code that the thread is executing. The following example uses the P:System.Threading.Thread.CurrentThread property to display information about the main application thread, another foreground thread, a background thread, and a thread pool thread.
Instances of the T:System.Threading.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 T:System.Threading.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 T:System.Threading.ThreadPool class.
Task-based asynchronous operations automatically execute on thread pool threads. Task-based asynchronous operations use the T:System.Threading.Tasks.Task and T:System.Threading.Tasks.Task`1 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 P:System.Threading.Thread.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.
Each thread has a culture, represented by the P:System.Threading.Thread.CurrentCulture property, and a UI culture, represented by the P:System.Threading.Thread.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 M:System.Threading.Thread.#ctor(System.Threading.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 T:System.Globalization.CultureInfo class topic.
This is not true of threads that execute asynchronous operations for apps that target the net_v46 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 T:System.Globalization.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 T:System.Globalization.CultureInfo object that represents that culture to the T:System.Threading.ParameterizedThreadStart delegate or the M:System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback,System.Object) method.
For apps running on the net_v45 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 P:System.Globalization.CultureInfo.DefaultThreadCurrentCulture and P:System.Globalization.CultureInfo.DefaultThreadCurrentUICulture properties. Note that this is a per-application domain setting.
For more information and examples, see the "Culture and threads" section of the T:System.Globalization.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. P:System.Threading.Thread.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 M:System.Threading.Thread.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 P:System.Threading.Thread.ManagedThreadId property is assigned by the runtime and uniquely identifies a thread within its process.
An operating-system ThreadIdhttps://msdn.microsoft.com/library/windows/desktop/ms683233.aspx 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 APIhttps://msdn.microsoft.com/library/ms404385.aspx 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 T:System.Threading.ThreadState property.
A scheduling priority level, which is defined by the T:System.Threading.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 P:System.Threading.Thread.IsThreadPoolThread property, which indicates whether a thread is a thread pool thread.
The P:System.Threading.Thread.IsBackground property. For more information, see the Foreground and background threads section.
To view the .NET Framework source code for the T:System.Threading.Thread class, see the Reference Sourcehttp://referencesource.microsoft.com/#mscorlib/system/threading/thread.cs#3980e012bae82e96. 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 instructionshttp://referencesource.microsoft.com/.
The following example demonstrates simple threading functionality.
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.
Verfügbar seit 1.1
Unterstützt in: portierbare .NET-Plattformen
Verfügbar seit 2.0
Windows Phone Silverlight
Verfügbar seit 7.0
This type is thread safe.