C # Comprehensive Revelation--elaborate multithreading (on)

Source: Internet
Author: User
Tags terminates thread class time interval

Introduction

This article mainly from the basic use of thread, the CLR thread pool in the development of worker threads and I/O threads, parallel operations PLINQ and other aspects of the development of multithreading.
The BeginInvoke method of the delegate and the callback function are most commonly used.
And I/O thread may easily be ignored by everyone, in fact, in the development of multithreaded systems, should pay more attention to the operation of I/O threads. Especially in asp.net development, perhaps more people will only pay attention to using AJAX on the client or using UpdatePanel on the server side. In fact, it is reasonable to use I/O threads to reduce the pressure of IIS as much as possible when communicating items or file downloads.
Parallel programming is an asynchronous operation which is popularized in Framework4.0, and it is worth studying more deeply.
I hope this article can be helpful to your study, where there are errors and omissions to please comment.

Directory

The definition of a thread

Second, the basic knowledge of the thread

Third, the ThreadStart way to achieve multithreading

Worker threads of the CLR thread pool

V. I/O threads for the CLR thread pool

VI, asynchronous SqlCommand

Vii. Parallel Programming and PLINQ

VIII. Timer and lock

the definition of a thread

1.1 process, application domain, and thread relationships

A process is a basic concept in a Windows system that contains the resources needed to run a program. Processes are relatively independent, one process cannot access data from another process (unless you are using distributed computing), the failure of one process does not affect the operation of other processes, and Windows systems use processes to divide work into separate areas. A process can be understood as a basic boundary of a program.

An application domain (AppDomain) is a logical area in which a program runs, and it can be considered a lightweight process. NET assembly is running in the application domain, a process can contain multiple application domains, and an application domain can contain multiple assemblies. One or more context contexts are included in an application domain, and the context of the CLR allows the state of some special objects to be placed in different containers.

Threads (thread) is the basic execution unit in a process, and the first thread that executes at the process portal is considered to be the main thread of the process. In a. NET application, the main () method is used as the portal, and the system automatically creates a main thread when this method is called. Threads consist primarily of CPU registers, call stacks, and thread local memory (thread native STORAGE,TLS). CPU registers mainly record the state of the currently executing thread, the call stack is used primarily to maintain the memory and data that the thread calls, and TLS is used primarily to hold the thread's state information.

The process, application domain, and thread relationships can include multiple application domains within a process, as well as multiple threads, and threads can also travel through multiple application domains. At the same time, however, threads will only be in one application domain.


Because this article is about threading technology as a topic, the introduction to processes, application domains ends here. The technology for processes, threads, and application domains is described in detail in the "C # Comprehensive disclosure-detailing processes, application domains, and contexts."

more than 1.2 threads

Within one unit time slice of a single CPU system, the CPU can only run a single thread, depending on the priority level of the thread. If the thread fails to complete execution at the unit time, the system saves the state information of the threads to the thread's local memory (TLS) so that it can resume execution the next time it executes. And multithreading is just a fake image brought by the system, it is in multiple unit time to switch multiple threads. Because the switch is frequent and the unit time is very short, multithreading can be seen as running simultaneously.

The proper use of multithreading can improve the performance of the system, such as: the use of multiple threads when the system requests large volumes of data, the output of the data to the asynchronous thread, so that the main thread to maintain its stability to deal with other problems. However, it needs to be noted that because the CPU will take a lot of time to switch on the thread, so excessive use of multithreading can lead to performance degradation.

Back to Table of contents

second, the basic knowledge of the thread

2.1 System.Threading.Thread Class

System.Threading.Thread is the underlying class used to control threads, which control the creation, suspension, stop, and destruction of a thread in the current application domain.

It includes the following common common properties:

Property name Description
CurrentContext Gets the current context in which the thread is executing.
CurrentThread Gets the currently running thread.
ExecutionContext Gets a ExecutionContext object that contains information about the various contexts of the current thread.
IsAlive Gets a value that indicates the execution state of the current thread.
IsBackground Gets or sets a value that indicates whether a thread is a background thread.
Isthreadpoolthread Gets a value that indicates whether the thread belongs to the managed thread pool.
Managedthreadid Gets the unique identifier of the current managed thread.
Name Gets or sets the name of the thread.
Priority Gets or sets a value that indicates the scheduling priority of the thread.
ThreadState Gets a value that contains the state of the current thread.

 

2.1.1-thread identifier

Managedthreadid is a unique identifier that confirms the thread, which in most cases identifies the thread through Thread.managedthreadid. While name is a variable value, by default, name is NULL, and developers can set the name of the thread by program, but this is only an accessibility feature.

 

2.1. Priority level of 2 threads

. NET sets the priority property for the thread to define the priority level of the thread execution, which contains 5 options, where normal is the default value. The priority level of a thread should not be set casually unless the system has special requirements.

member name Description
Lowest Thread can be scheduled after any other priority.
BelowNormal You can schedule threads to be after a thread that has the Normal priority, before a thread with Lowest priority.
Normal The default selection. You can schedule threads to be preceded by a thread with a abovenormal priority, before a thread with a belownormal priority.
AboveNormal You can schedule threads to be after a thread that has a highest priority, before a thread that has the Normal priority.
Highest You can schedule threads before a thread with any other priority.

 

2.1.3 State of the thread

By ThreadState you can detect that threads are in unstarted, sleeping, Running, and so on, and that they provide more specific information than the IsAlive attribute.

As mentioned earlier, an application domain may include multiple contexts, and the current context of the thread can be obtained by CurrentContext.

CurrentThread is the most commonly used property, which is used to get the currently running thread.

 

the method of 2.1.4 System.Threading.Thread

Thread includes several methods to control the creation, suspension, stopping, and destruction of threads, which are frequently used in later examples.

Method Name Description
Abort () Terminates this thread.
GetDomain () Returns the current domain in which the current thread is running.
Getdomainid () Returns the current domain ID in which the current thread is running.
Interrupt () Interrupts a thread that is in the WaitSleepJoin thread state.
Join () has been overloaded. Blocks the calling thread until a thread terminates.
Resume () Continue running the suspended thread.
Start () Executes this thread.
Suspend () Suspends the current thread, which does not work if the current thread is already in a suspended state
Sleep () Suspend the running thread for some time.

2.1.5 Development Example

The following example shows the current thread information through thread

1         static void Main (string[] args)
 2         {
 3             thread thread = thread.currentthread;
 4             Thread. Name = "Main Thread";
 5             String threadmessage = string. Format (' thread id:{0}\n current    appdomainid:{1}\n    ' +
 6                 ' current contextid:{2}\n    thread name:{3}\n    "+
 7                 " thread state:{4}\n    thread priority:{5}\n,
 8                 thread. Managedthreadid, Thread.getdomainid (), Thread.CurrentContext.ContextID,
 9                 Thread. Name, Thread. ThreadState, Thread. Priority);             Console.WriteLine (threadmessage);
One             Console.readkey ();
The         }

Run results

2.2 system.threading Namespaces

The

provides multiple ways to build multithreaded applications within the System.Threading namespace, where ThreadPool and thread are most commonly used in multithreaded development, where a CLR thread pool is specifically configured to manage the running of threads. This CLR thread pool is managed by the ThreadPool class. While thread is the most straightforward way to manage threads, the following sections describe the content in more detail.

class description
A Utoresetevent Notifies the waiting thread that an event has occurred. This class cannot be inherited. The
executioncontext manages the execution context of the current thread. This class cannot be inherited. The
interlocked provides atomic operations for variables that are shared by multiple threads. The
Monitor provides a mechanism for synchronizing access to objects. The
Mutex is a synchronization primitive and can also be used for interprocess synchronization.
thread creates and controls the thread, sets its precedence, and obtains its status. The exception that is thrown when
threadabortexception is invoked on the Abort method. This class cannot be inherited.
ThreadPool provides a thread pool that can be used to send work items, handle asynchronous I/O, wait on behalf of other threads, and handle timers. The
Timeout contains constants that specify an infinite length of time. This class cannot be inherited. The
Timer provides a mechanism for executing a method at a specified time interval. This class cannot be inherited. The
WaitHandle encapsulates an operating system-specific object that waits for exclusive access to a shared resource.


The system.threading contains a number of commonly used delegates in the following table, where ThreadStart, Parameterizedthreadstart are the most commonly used delegates.
Threads generated by ThreadStart are the most straightforward way, but generated by ThreadStart is not managed by the thread pool.
The Parameterizedthreadstart is designed for asynchronous triggering of parameters, and will be explained in the next section.

Delegate Description
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.