Thread crazy ------ asynchronous operations restricted by computing, thread ------ asynchronous

Source: Internet
Author: User

Thread crazy ------ asynchronous operations restricted by computing, thread ------ asynchronous
Preface

Asynchronous restriction operations mainly apply to other execution threads, such as rule checking, audio or video data transcoding, and generating graphical thumbnail. in financial and construction engineering applications, computing restrictions are also very common.

 

CLR Thread Pool

A thread pool is a collection of threads that can be used by your applications. Each thread pool is shared by all the AppDomains controlled by CLR. If a process loads multiple CLR, each CLR has its own thread pool. During CLR initialization, there is no thread in the thread pool, and a queue request is maintained inside the thread pool. When an application executes an asynchronous process, call a method to append a record item to the queue of the thread pool. The code of the thread pool extracts the record item from the queue and distributes the record item to a thread pool thread, if there is no thread in the thread pool, a new thread will be created. After the task is executed, the thread will not be destroyed. The thread pool will be returned and enter the idle state, waiting to respond to another request without consuming additional performance.

However, when a thread is idle for a while, the thread will automatically release resources. The purpose of using the thread pool is not to worry about the performance loss caused by thread creation and destruction.

 

Simple computing restrictions

A method defined by the ThreadPool class:

Static Boolean QueueUserWorkItem (WaitCallback callBack, object obj );

Method Description: Add a work item and optional State data to the thread pool, and then execute this work item to pass an obj parameter to the method.

Code demo

1 class Program 2 {3 static void Main (string [] args) 4 {5 Console. writeLine ("program execution started"); 6 ThreadPool. queueUserWorkItem (ComputerSort, 6); 7 Console. writeLine ("simulate other operations for 5 s"); 8 Thread. sleep (5000); 9 Console. writeLine ("click Enter to exit the program"); 10 Console. readLine (); 11} 12 13 private static void ComputerSort (object obj) 14 {15 Console. writeLine ("Thread Pool start execution parameter = {0}", obj. toString (); 16} 17}

Display result

We found that the execution sequence of the output changes because the two methods run asynchronously. The Windwos scheduler decides to schedule the thread first. If it is a multi-core CPU, it may schedule them at the same time.

Execution Context

Each thread is associated with two execution context data structures. The execution context includes security settings (compression stack, Principal attribute, Windows identity), host settings, and logical call context data.

Ideally, whenever a thread uses another thread (Auxiliary thread) to execute a task, the execution context of the former should flow to the latter, make sure that all operations performed by the auxiliary thread use the same security settings and host settings.

By blocking execution context flow, the performance of applications can be improved, especially for server applications. The client performance is average.

Example code:

 

1 static void Main (string [] args) 2 {3 4 // put data into the logic context of the Main thread 5 CallContext. logicalSetData ("Name", "Tom"); 6 7 ThreadPool. queueUserWorkItem (p => 8 {9 Console. writeLine ("Name = {0}", CallContext. logicalGetData ("Name"); 10}); 11 12 ExecutionContext. suppressFlow (); 13 14 ThreadPool. queueUserWorkItem (p => 15 {16 Console. writeLine ("Name = {0}", CallContext. logicalGetData ("Name"); 17}); 18 19 ExecutionContext. restoreFlow (); 20 21 ThreadPool. queueUserWorkItem (p => 22 {23 Console. writeLine ("Name = {0}", CallContext. logicalGetData ("Name"); 24}); 25 26 Console. readLine (); 27 28}

 

Collaborative cancellation and timeout

Canceling long-running computing restrictions is a necessary operation ,.. Net provides a standard cancel operation mode. The following types must be used regardless of the Code that executes the operation or the code that tries to cancel the operation.

System. Threading. CancellationTokenSource -------> This object contains all the statuses related to management cancellation. You can obtain one or more CancellationToken instances from its Token attributes,

1 static void Main (string [] args) 2 {3 CancellationTokenSource cts = new CancellationTokenSource (); 4 5 ThreadPool. queueUserWorkItem (state => Count (cts. token, 100); 6 7 Console. writeLine ("Enter to stop computing"); 8 9 Console. readLine (); 10 11 cts. cancel (); 12 13 Console. readLine (); 14} 15 16 private static void Count (CancellationToken token, int count) 17 {18 for (int I = 0; I <= count; I ++) 19 {20 if (token. isCancellationRequested) 21 {22 Console. writeLine ("received cancellation signal"); 23 break; 24} 25 Console. writeLine ("I = {0}", I); 26 Thread. sleep (1000); 27} 28}

If you want to call the CancellationTokenSource's Register Method to Register one or more methods called when canceling a CancellationTokenSource, you must pass an Action <object> Delegate to the method, a callback is to be passed through the delegate method, and a Boolean value that specifies whether to use the SynchroinzationContent of the calling thread to call the delegate.

 

1 cts. Token. Register () => 2 {3 Console. WriteLine ("Call the callback function after receiving the cancellation signal"); 4 });

 

In many cases, we need to cancel the operation after a period of time. For example, the server application may calculate the request according to the client, but must respond within two seconds, whether or not the session is completed, you must end the session. In. NET 4.5, CacncellationTokenSource provides a CancelAfter method.

1  public void CancelAfter(int millisecondsDelay)

 

The content in this chapter is explained here. In the next section, we will continue to thread crazy-task.

 

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.