ASP. NET multi-thread programming

Source: Internet
Author: User

* Summary
. Thread principle Overview
.. Multi-thread programming under. net
. Asynchronous programming
. ASP. NET multi-thread programming

* Basic thread concepts
. A thread is the basic atomic unit of program execution. A process can be composed of multiple threads.
. Each thread maintains the exception handling program, scheduling priority, and a group of systems used to save the thread context structure before scheduling the thread. The thread context includes all the information required for the thread to seamlessly continue execution in the thread host process address space, including the CPU register group and stack of the thread.
. In distributed programming, correct use of threads can improve the performance and running efficiency of applications. The implementation principle is to divide a process into multiple threads and then let them execute concurrently and asynchronously to improve the running efficiency.
. Concurrent execution does not occupy the CPU at the same time. At any time, only one thread occupies the CPU, But they compete for the CPU more frequently and feel that they are all running.

* When is a thread used?
. Generally, if multiple threads need to seize a certain resource or several resources during execution, it is best not to use Asynchronous threads for execution. Because they are executed concurrently, it is likely to compete for a certain resource at the same time.

If the source has a CPU, either the resource allocation algorithm is executed (for example, it takes time to determine which thread has a high priority) or the time slice algorithm (in this way, the CPU is polling/transferred/the CPU is transferred out ).

Time required)
. If the system resources required by multiple threads are relatively uniform, they can be executed asynchronously and concurrently.

* Disadvantages of using threads
. The system will be used internally for context information required by processes and threads. Therefore, the number of appdomain objects and threads of processes that can be created is limited by the available memory.
. A large number of threads will occupy a large amount of processing time. If there are too many threads, most of them will not produce significant progress. If most of the current threads are in one process

The scheduling frequency of threads in the process is very low.
. Using many threads to control code is complex and may produce many errors.
. To destroy a thread, you must understand the possible problems and handle them.
*. Net multi-thread programming
. Use of Thread class
. Thread with Parameters
. Delegate and thread.
. Application domain
. Operation in the critical section.

* System. threading
. Provides classes and interfaces that enable multi-threaded programming. This namespace includes the threadpool class for managing thread groups so that the delegate's Timer class can be called after the specified time and

The mutex class used to synchronize mutex threads. System. Threading also provides classes for Thread Scheduling and waiting for parsing of dead-end notifications.
. Using system. Threading;

* Thread class
. A. Start thread: Create and start a thread:
-Tread thead1 = new tread (New threadstart (count); the count is the function to be executed by the new thread.
. B. Killing threads
-Before killing a thread, you 'd better determine whether the thread is still alive (through the isalive attribute). Then you can call the abort method to kill the thread.
. C. Pause the thread
-Sleep a running thread for a period of time. For example, thread. Sleep (1000) is used to sleep the thread for 1 second.
. D. Priority
-Threadpriority attribute in the Thread class, which is used to set the priority. However, the operating system cannot accept this priority. The priority of a thread can be divided into five types:
Normal, abovenormal, belownormal, highest, lowest.
. E. Thread Suspension
-The suspend method of the thread class is used to suspend a thread. This thread can continue execution until resume is called. If the thread has been suspended, it will not work.
. F. Restore the thread
-The resume method is used to restore a suspended thread to continue execution. It does not work if the thread is not suspended.

. A thread's method does not contain any parameters, nor returns any value. Its naming rules are the same as those for general functions. It can be either static or non-static.

). After it is executed, the corresponding thread ends, and the isalive attribute of the thread object is set to false.
.. Net public Language Runtime (CLR) can distinguish two different types of threads: foreground thread and background thread. The difference between the two is that the application must run all the foreground threads.

For background threads, the application can automatically end when the program exits.
. Whether a thread is a foreground thread or a background thread is determined by its isbackground attribute.

* Threads with Parameters
. When creating a thread, a new instance of the thread class will be created using the threadstart delegate as its unique parameter constructor. However, the thread does not start execution before calling the start method. Call "open

Starts from the first line of the method referenced by threadstart.
. When a threadstart delegate is created, the method used to process the event is identified. To associate an event handler with an event, add an instance of the Delegate to the event. When an event occurs

Use an event handler unless the delegate is removed.
. A thread can also call methods with parameters, even if the threadstart delegate only includes one parameter-an object indicating the state. It is exactly this object that should send parameters to the called method.

* Delegation and thread
1. Commission Basis
-Purpose of delegation: Pass functions as parameters
-Similar to function pointers in C ++
-Is the basis for event processing.
-The function pointer can only reference static functions, but the delegate can reference static methods and instance methods. When a delegate references an instance method, the delegate not only stores the reference to the method entry point, but also stores

Reference of the class instance using this method.
-Delegate statement:
. Delegate double process (double db1 );
. Delegate function return type name delegate name (function parameter)

* Delegated instance
Delegate void mydelegate (int I); // delegate statement
Class Program
{
Public static void main ()
{
Takesadelegate (New mydelegate (delegatefunction ));
}
Public static void takesadelegate (mydelegate somefunction) {somefunction (21 );}
Public static void delegatefunction (int I)
{System. Console. writeline ("called by Delegate with number; {0}", I );}
}

* Application domain
. The operating system and runtime environment usually provide some form of isolation between applications. To ensure that the code running in one application does not adversely affect other unrelated applications

This isolation is required.
.. Net adds an isolation layer called the application domain appdomain, which is an internal logical independent part.
. The application domain provides secure and universal processing units, which can be used by the Common Language Runtime Library to provide isolation between applications. Errors in one application do not affect other applications.

.
. Use the application domain:
-A single application can be stopped without stopping the entire process.
-Code running in one application cannot directly access code or resources in other applications.
-The scope of the Code behavior is determined by the application where it runs.
-The permissions granted to the code can be controlled by the application domain where the code runs.

* Application domains and threads
. Line and process are the operating system structures used by the Common Language Runtime Library to execute code. At runtime, all managed code is loaded into an application domain and run by a specific operating system thread.
. There is no one-to-one correlation between application domains and threads. At any given time, several threads can be executed in a single application domain, and the specific threads are not limited to a single application.

Domain. That is to say, threads can freely span application domain boundaries, without creating new threads for each application domain.
. At any given time, each line is executed in an application domain. The Runtime Library tracks which threads are running in which application domains. By calling the thread. getdomain Method

, You can determine the thread execution domain at any time.

* Critical section operations
. Lock Keyword: Mark a statement block as a critical section, and another thread does not enter the critical section.
. Interlocked class: Provides atomic operations for variables shared by multiple threads. The increment and decrement Methods increase or decrease variables and store the result values in a single operation.
. Monitor class: provides a mechanism to synchronize access to objects.
The monitor class grants an object lock to a single thread to control access to the object. Use the enter and exit methods to mark the beginning and end of a critical section.

* Asynchronous Delegation
. Asynchronous delegation provides the ability to call synchronous Methods asynchronously.
. When a delegate is synchronously called, The Calling method calls the target method directly to the current thread. If the compiler supports asynchronous delegation, it will generate the call method and begininvoke and endinvoke

Method.
. If you call the begininvoke method, the common language runtime queues requests and immediately returns them to the caller. This method will be called for threads from the thread pool. Original request submitted

The thread freely continues to execute in parallel with the target method, which runs on the thread pool thread.
. In the callback, use the endinvoke method to obtain the return value and input/output parameters. If you do not specify a callback for begininvoke, you can use endinvoke on the original thread that submits the request.

* Thread processing in ASP. NET
. In order to effectively provide services for multiple client requests, the web server requires a large amount of concurrency. This is to provide services and execute jobs for requests by starting multiple processes and/or generating multiple threads.

.
. ASP. NET is no exception. It uses multiple threads in each worker to provide services for requests.
. ASP. NET uses the CLR thread pool within the process range to provide services for requests. The pool size can be configured in the processmodel element of machine. config, and is set to 25 secondary nodes by default.

Thread and 25 I/O threads.
. The same applies to the associated modules of the application for each incoming request. To avoid repeated application and module allocation in a complex manner, each appdomain maintains an application

And module pool. The maximum size of the application pool is the same as that of the thread pool. Therefore, by default, each secondary process can process up to 25 requests concurrently. Each request has its own

Application and module set.

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.