Asp. NET essence theory reading----thread and async

Source: Internet
Author: User

Thread

Summary: The operating system manages the execution of the program through threading

The data structure of the thread: 1. The core object of the thread (containing the current register state of the thread), when the calling thread-the register state is loaded into the CPU.

2. Thread environment block TEB: Memory in a piece of user mode

3. User-mode stack: storage of local variables and parameters for user programs

4. Kernel-mode stacks: stacks for accessing the operating system

Thread classification: foreground thread and background thread. PS: All foreground threads terminate, program terminates.

Thread Execution Task classification: worker threads and I/O threads

Worker threads: compute-intensive tasks, full utilization of CPU and thread resources

I/O Threads: CPUs do not have to participate in the processing process

Thread pool

Creating and starting a thread

Because the thread is used to represent the execution of the code, it needs to be done through a delegate, 3 common thread delegates

1.ThreadStart delegate

public delegate void ThreadStart ();

2.ParameterizedThreadStart delegate

public delegate void Parameterizedthreadstart (Object obj)

3.TimerCallback delegate

Timer class implementation

Public Timer (TimerCallback//Time-to-execute delegate

, state//passed parameters

, Duetime//Create a time difference to the first execution

, Period//time interval

)

The state of the thread System.Thread.ThreadState

  

Thread context gets thread data ExecutionContext

Asynchronous Programming Mode APM

In order to support APM mode processing,. NET for long-consuming operations, the begin and end methods are provided, and when begin is called, the first step of the asynchronous thread is started, and the third-step callback method is saved, and the third operation executes on the I/O thread of the online pool.

Example: Stream read operation

1. Synchronization

public override int Read (byte[] array, int offset, int count);

2. Asynchronous, the first and third steps are as follows

public override IAsyncResult BeginRead (

Byte[] Array

, int offset

, int numbytes

, AsyncCallback Usercallback

, Object StateObject)

Usercallback: The callback method that the system needs to invoke after the asynchronous call is completed

StateObject: A user-defined Parameter object passed to the callback method, in general, an object that uses an asynchronous operation to complete the end operation.

public override int EndRead (IAsyncResult syncresult);

New FileStream (path,open); IAsyncResult result= fs. BeginRead (buffer,0,4096,delegate(IAsyncResult ar) {       int length= Fs. EndRead (AR);},fs);

Event-based Asynchronous programming pattern EPM

A class that supports EPM will have one or more methods with a suffix of async, and an event with the corresponding name completed suffix

The Async method initiates asynchronous processing, while the completed event declares the completion of asynchronous processing through events

The completed handler must be called regardless of processing completion, exception occurrence, and termination of asynchronous processing

Example: WebClient sends a request OpenReadAsync

public void OpenReadAsync (Uri address)

Public event Openreadcompletedeventhandler openreadcompleted

Handle the event

 Public Static void OpenReadCallback2 (Object Sender,openreadcompletedeventargs e) {stream reply=null; StreamReader s=null; Try {Reply=(stream) e.result;s=new  StreamReader (reply); Console.WriteLine (S.readtoend ());}

Status and synchronization issues for asynchronous threads


public interface IAsyncResult

{

Object Asyncstate{get;}

WaitHandle Asyncwatihanle{get;}

BOOL Completedsynchronously{get;}

BOOL Iscompleted{get;}

}

Handling asynchronous issues in pipelines

Freeing a thread from waiting

When starting a thread operation, save the third method that ends the asynchronous operation, immediately after the first step, the first thread is finished, the second waits for the processing to complete, the third processing method is fetched, a thread is retrieved to perform the third part, and after completion, the thread's original subsequent steps are resumed.

NeXTSTEP class PublicNextStep (EndEventHandler handler) { This. _endhandler=handler;} Public voidAsyncCallback (IAsyncResult ar) { This. _endhandler (AR);}       ReadFile class Package Iasyncreault Beginreadfile (Object Sender,evnetargs E, AsyncCallback cb, Object Extradata); voidendreadfile (IAsyncResult ar); Stepdemo package This._beginhandler and This._endhandler Public voiddoasyncbeginwork () {NEXTSETP step=New( This. _endhandler);  This. Beginhandler ( This,, step. AsyncCallback,NULL);} Call Stepdemo Demo=NewStepdemo (); ReadFile RF=NewReadFile ();d emo. Adddowork (RF. Beginhandler,rf. Endhandler);d Emo. Doasyncbeiginwork ();

thread Pool

public static Class ThreadPool

. NET maintains an application-shared thread pool in each thread, and the thread pool provides queues that can use a small number of threads to accomplish the tasks of most threads

How the thread pool works:

1. Thread pool threads are divided into: compute-intensive worker threads, I/O threads

2. Thread pool threads get the corresponding task from the corresponding task queue to process, and after completion, continue to get the task from the queue, if not, after waiting for some time, the thread will be destroyed

Join worker Threads

1.public delegate void Waitcallback{object State}

2.public static void Main () {

ThreadPool.QueueUserWorkItem (New WaitCallback (ThreadProc));

static void ThreadProc (object stateInfo) {};

Join I/O thread

The method that begins by invoking begin is the I/O task queue that queues threads to the thread pool

asynchronous threads in the HttpApplication

When the server receives a request, httpruntime gets a HttpApplication object processing request from the HttpApplication pool, and the processing of the request is queued to the thread pool.

Asp. NET essence theory reading----thread and async

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.