[. NET object-oriented programming advanced] (18) Multithreading (multithreading) (iii) Improve program performance with multithreading (bottom)

Source: Internet
Author: User

[. NET object-oriented programming advanced] (18) Multithreading (multithreading) (ii) Improve program performance with multithreading (bottom)

This section is guided by:

The previous section described the use of thread locks and thread notifications to handle resource-sharing issues in threading synchronization, which is the rationale for multithreading.

. NET 4.0 The subsequent implementation of multithreading has become much simpler.

This section mainly discusses . NET4.0 new features for multi-threading--Use the TAsk class to create multithreading.

Pre-Read Prerequisites:

A. LINQ uses [. NET object-oriented Programming Fundamentals] (LINQ)

B. Generics [. NET object-oriented programming fundamentals] (18) generics

1. thread pool ThreadPool

Before introducing the multi-line assigns feature after 4.0, it is simple to say a thread pool.

Through the front-facing multi-threaded learning, we find that multi-threading is not difficult to create and use, it is difficult to manage multi-threaded, especially the number of threads in many cases, how to manage and release resources. You need to use a thread pool to resolve.

In short, the thread pool is. NET provides an object container for storing threads.

Thread pool threads are divided into two categories: worker threads and IO threads .
The thread pool is a form of multithreading that adds tasks to the queue during processing, and then automatically starts those tasks after the thread is created.

For the thread pool, you can call the System.Threading.ThreadPool.QueueUserWorkItem (System.Threading.WaitCallback) method with the delegate of the procedure you want to run

The following is an example of a thread pool:

Set up a static field to create the total number of threads first:

Static ReadOnly int ;

To create a thread using the thread pool:

//set minimum thread and maximum number of threadsThreadpool.setminthreads (2,2); Threadpool.setmaxthreads ( -, -); for(inti =0; i < totalthreads; i++) {ThreadPool.QueueUserWorkItem (o={Thread.Sleep ( +); intA, B; Threadpool.getavailablethreads ( outA outb); Console.WriteLine (string. Format ("({0}/{1}) #{2}: {3}", A, B, Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString ())); });} Console.WriteLine ("Main thread Complete");

The results of the operation are as follows:

2. Task class

Using the ThreadPool queueuserworkitem () method to initiate an asynchronous thread execution is simple, But the biggest problem with this approach is that there is no built-in mechanism to let you know when the operation is complete, and there is no built-in mechanism to get a return value after the operation is complete. For this reason, after the. NET 4.0 , we can use the Task class in System.Threading.Tasks . This is also the recommended practice for multi-threading after. NET 4.0.

Constructs a task<t> object and passes the return type of an operation for the generic T parameter.

the task class can create multiple threads using several methods, described in detail below.

2.1 Using the Factory Property

Task instances can be created in a variety of different ways. The most common approach is to use the Factory property of a task to retrieve a TaskFactory instance that can be used to create multiple uses .

For example, to create a Task that runs an operation , you can use the factory's StartNew method:           

// The simplest example of threading Task.Factory.StartNew (() ={    Console.WriteLine (" I am a thread created using the Factory property " );});

The results of the operation are as follows:

If you want to create a task simply, it is easy to create it using Factory.newstart ().

If you attach more customizations and set specific properties to the task you created, continue looking down.

2.2 using T-Ask instances for multithreading

// simple task Instance creation thread action<Object> Action = (object obj) = ={    Console.WriteLine ("  Task={0}, Obj={1}, thread={2}"new" parameter "); T1. Start ();

The results of the operation are as follows:

//abbreviated above instance, and create 100 threadsSystem.Diagnostics.Stopwatch Watch =System.Diagnostics.Stopwatch.StartNew ();intm = -; Task[] Tasks=NewTask[m]; for(inti =0; I < m; i++) {Tasks[i]=NewTask (Objectobj) ={Thread.Sleep ( $); Console.WriteLine ("task={0}, Obj={1}, thread={2}, Current time: {3}", Task.currentid, obj.        ToString (), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.ToString ()); }, "Parameters"+i.tostring ()); Tasks[i].           Start ();} Task.waitall (tasks); Console.WriteLine ("thread time: {0}, Current time: {1}", watch. Elapsedmilliseconds,system.datetime.now.tostring ());

The results of the operation are as follows:

2.3 Task Incoming parameters

The above describes the use of an Action delegate to complete the process, then to the thread to pass in parameters, you can use system.action<object> to complete.

An example of passing in a parameter:

/// <summary> /// a method of a parameter /// </summary> /// <param name= "parameter" ></param> Static void MyMethod (string  parameter) {    Console.WriteLine ("{0}" , parameter);}

The call is as follows:

// task passes in a parameter New " AAA " ); Mytask.start ();

The results of the operation are as follows:

Pass in multiple parameters as follows:

/// <summary>///methods for multiple parameters/// </summary>/// <param name= "Parameter1" ></param>/// <param name= "Parameter2" ></param>/// <param name= "Parameter3" ></param>Static voidMyMethod (stringParameter1,intparameter2,datetime Parameter3) {Console.WriteLine ("{0} {1} {2}", Parameter1,parameter2. ToString (), Parameter3. ToString ());}

The call is as follows:

// task passed in multiple parameters  for (int1; i++) {                  new Task () = {MyMethod (" my Thread  ", I, DateTime.Now);}). Start ();    Thread.Sleep (+);}

The results of the operation are as follows:

For passing in multiple parameters, you can use a parameterless delegate to wrap a multi-parameter method to complete.

2.4 The result of a task

To get the result of a task, you use task<t> to instantiate a task when you create the task.

The T is the type of the result returned after the task execution is complete.

The result property of a task instance can be obtained.

System.Diagnostics.Stopwatch Watch =System.Diagnostics.Stopwatch.StartNew (); Task<int> MyTask =Newtask<int> (() ={    intsum =0;  for(inti =0; I <10000; i++) Sum+=i; returnsum;});           Mytask.start (); Console.WriteLine ("result: {0} time consuming: {1}", Mytask.result,watch. Elapsedmilliseconds);

The results of the operation are as follows:

Use the Factory property to complete the example above:

//Use the Factory property to createSystem.Diagnostics.Stopwatch Watchsecond =System.Diagnostics.Stopwatch.StartNew (); Task<int> Mytasksecond = task.factory.startnew<int> (() ={    intsum =0;  for(inti =0; I <10000; i++) Sum+=i; returnsum;}); Console.WriteLine ("result: {0} time consuming: {1}", Mytasksecond.result, watchsecond.elapsedmilliseconds);

The results of the operation are as follows:

Multithreading in addition to some of the basic knowledge, in the processing of various parallel tasks and the use of multi-core programming, small partners can refer to specialized in multi-threaded book learning.

Want to thoroughly in-depth study multithreading needs to slowly cultivate, accumulate unceasingly.

3. Highlights of this section:

A. This point simply introduces the use of thread pool ThreadPool;

B. Describes a parameter that uses a task for multi-threaded creation and tast to pass in and return results.

==============================================================================================

Back to Catalog

< If it is helpful to you, please remember to click on the recommendation Oh, if there is There is no understanding or error , please exchange >

< for those who have difficulty reading this series of articles, please read the basics of. NET object-oriented programmingfirst >

< REPRINT statement: Technology needs to share the spirit, welcome to reprint the article in this blog, but please specify copyright and url>

. NET Technology Exchange Group: 467189533

==============================================================================================

[. NET object-oriented programming advanced] (18) Multithreading (multithreading) (iii) Improve program performance with multithreading (bottom)

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.