Basics of Multithreading (ii)

Source: Internet
Author: User
Tags apm

Thread pool
    1. Because each time the thread is created and the thread is destroyed, CPU resources are consumed, so it can be optimized through the thread pool. The thread pool is a set of threads that have been created, which are used to fetch, run out of threads, and then put into the thread pool for other people to use.
    2. The thread pool cannot be used to fine-tune the threads (line Cheng stop, priority control, etc.).
    3. An important method of the ThreadPool class:
      1. static bool QueueUserWorkItem (WaitCallback callBack)
      2. static bool QueueUserWorkItem (WaitCallback callBack, Object state)//used to pass a parameter to the thread code
    4. Unless you want fine-grained control of threads, it is recommended that you use a thread pool because it is simple, performance-tuning, and better.

1 Static voidMain (string[] args)2         {3ThreadPool.QueueUserWorkItem (state =4             {5                  for(inti =0; I < -; i++)6                 {7 Console.WriteLine (i);8                 }9             });Ten}
View Code

1 Static voidMain (string[] args)2         {3             4              for(inti =0; I < -; i++)5             {6                 //path a line value by the second argument7ThreadPool.QueueUserWorkItem (state =8                 {9 Console.WriteLine (state);Ten }, i); One             } A Console.read (); -}
View CodeThree types of asynchronous programming models

Many of the class interfaces in. Net are designed with multithreading in mind, simplifying the development of multi-threaded threads. You don't have to write Waithandler and wait for these underlying code. Due to the development of history, the interface design of these classes has three different styles: EAP (*), APM (*) and TPL.

The current focus is on TPL.

1.EAP Style: similar to xmlhttprequest,send in Ajax is not done after processing, but in the onReadyStateChange event to notify the completion of processing

1WebClient WC =NewWebClient ();2Wc. downloadstringcompleted + =wc_downloadstringcompleted;3Wc. DownloadStringAsync (NewUri ("http://www.baidu.com"));4 Private voidWc_downloadstringcompleted (Objectsender, DownloadStringCompletedEventArgs e)5 {6 MessageBox.Show (e.result);7}
View Code

The advantage is simple, the disadvantage is when the implementation of complex business is very troublesome; The EAP class is characterized by an asynchronous method with a ***completed event. Less EAP-based analogies in. Net

2.APM Style: is an asynchronous programming model widely used in. Net legacy versions. An asynchronous method that uses APM returns an IAsyncResult object that has an important property AsyncWaitHandle, which is a synchronous signal that waits for the end of an asynchronous task to execute.

APM Features: The method name begins with BeginXXX, the return type is IAsyncResult, and the call ends with EndXxx. Net has the following common classes to support Apm:stream, SqlCommand, sockets, and so on.

TPL style: Yes. New features brought by Net4.0, more concise, convenient, now. NET platform has been used for a large area

Note If there is an await in the method, the method must be marked as async, and not all methods can be easily marked as async.

The event-handling methods in WinForm can be marked as async, an Action method in MVC, or it can be marked as async,

The Main method of the console cannot be marked as async.

TPL Features: The method ends with XXXAsync, and the return value type is the task<t> of the generic type. TPL allows us to write asynchronous programs in a linear fashion, eliminating the need for a bunch of callbacks and logic jumps like in EAP.

Note that the return value in the TPL is used directly, so try not to use some other method parsing, such as: Result ()

Write one of your own async methods

Ending with async is best, writing habits

Static task<string> f2async () {return task.run (() ={System.Thread.Sleep (  - )return"helloword! " ;});}

Basics of Multithreading (ii)

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.