[. Net Object-Oriented Programming (advanced)] (18) Multithreading (iii) improve program performance using Multithreading (II) and c object-oriented multi-threaded programming

Source: Internet
Author: User

[. Net Object-Oriented Programming (advanced)] (18) Multithreading (iii) improve program performance using Multithreading (II) and c object-oriented multi-threaded programming

[. Net Object-Oriented programming advanced] (18) Multithreading (2) Improve program performance using Multithreading (2)

This section introduces:

The above section describes how to use thread locks and thread notifications in thread synchronization to handle resource sharing issues. These are the basic principles of multithreading.

After. NET 4.0, the implementation of multithreading becomes simpler.

This section mainly discusses the new features of. NET4.0 multithreading-using the Task class to create multithreading.

Before reading:

A. Use [. net Object-Oriented Programming Basics] (20) Use

B. Generic [. net Object-Oriented Programming Basics] (18) Generic

1. ThreadPool

Before introducing the new features of multithreading after 4.0, let's briefly talk about the thread pool.

Through the multi-thread learning, we found that it is not difficult to create and use multiple threads. What is difficult is the management of multiple threads, especially how to manage and release resources when there are many threads. You need to use the thread pool to solve the problem.

In short, the thread pool is an object container provided by. NET to store threads.

Thread Pool threads are divided into two types: worker threads and IO threads.
A thread pool is a form of multi-threaded processing. during processing, tasks are added to the queue, and these tasks are automatically started after the thread is created.

For the thread pool, you can call the System. Threading. ThreadPool. QueueUserWorkItem (System. Threading. WaitCallback) method by using the delegate of the process to be run.

The following is an example of a thread pool:

First, set a static field for the total number of creation threads:

 static readonly int totalThreads = 20;

Use the thread pool to create a thread:

// Set the minimum thread and maximum thread count ThreadPool. setMinThreads (2, 2); ThreadPool. setMaxThreads (20, 20); for (int I = 0; I <totalThreads; I ++) {ThreadPool. queueUserWorkItem (o =>{ Thread. sleep (1000); int a, B; ThreadPool. getAvailableThreads (out a, out B); Console. writeLine (string. format ("({0}/{1}) #{2 }:{ 3}", a, B, Thread. currentThread. managedThreadId, DateTime. now. toString ();} Console. writeLine ("completed by the main thread ");

The running result is as follows:

 

2. Task class

It is easy to use the QueueUserWorkItem () method of ThreadPool to initiate an asynchronous thread execution, but the biggest problem with this method is that there is no built-in mechanism to let you know when the operation will be completed, is there a built-in mechanism to obtain a return value after the operation is complete. Therefore, after. NET 4.0, we can use the Task class in System. Threading. Tasks. This is also a recommended practice for multithreading after. NET 4.0.

Construct a Task <T> object and pass the return type of an operation for the generic T parameter.

The Task class can be used to create multiple threads. The following describes in detail.

2.1 use the Factory property 

Task instances can be created in different ways. The most common method is to use the Factory attribute of a task to retrieve and create TaskFactory instances for multiple purposes.

For example, to create a Task for running operations, you can use the StartNew method of the factory:

// The simplest thread example Task. Factory. StartNew () => {Console. WriteLine ("I Am a thread created using the Factory attribute ");});

The running result is as follows:

To create a Task, use Factory. NewStart.

If you want to add more customization and set specific attributes to the created Task, go on to the page.

2.2 Use Task instances to implement Multithreading 

// Simple Task instance creation thread Action <object> action = (object obj) => {Console. writeLine ("Task = {0}, obj = {1}, Thread = {2}", Task. currentId, obj. toString (), Thread. currentThread. managedThreadId) ;}; Task t1 = new Task (action, "parameter"); t1.Start ();

The running result is as follows:

 

// Abbreviation of the above instance, and create 100 threads System. diagnostics. stopwatch watch = System. diagnostics. stopwatch. startNew (); int m = 100; Task [] tasks = new Task [m]; for (int I = 0; I <m; I ++) {tasks [I] = new Task (object obj) => {Thread. sleep (1, 200); Console. writeLine ("Task = {0}, obj = {1}, Thread = {2}, current time: {3}", Task. currentId, obj. toString (), Thread. currentThread. managedThreadId, System. dateTime. now. toString () ;}, "parameter" + I. toString (); tasks [I]. start ();} Task. waitAll (tasks); Console. writeLine ("thread time: {0}, current time: {1}", watch. elapsedMilliseconds, System. dateTime. now. toString ());

The running result is as follows:

2.3 Task input parameters

The preceding section describes how to use an Action delegate to complete any process. You can use System. Action <object> to input parameters to the thread.

Example of passing in a parameter:

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

The call is as follows:

// Input a parameter Task myTask = new Task (parameter) => MyMethod (parameter. ToString (), "aaa"); myTask. Start ();

The running result is as follows:

Multiple parameters are input as follows:

/// <Summary> /// method of multiple parameters /// </summary> /// <param name = "parameter1"> </param> // <param name = "parameter2"> </param> // <param name = "parameter3"> </param> static void MyMethod (string parameter1, int parameter2, DateTime parameter3) {Console. writeLine ("{0} {1} {2}", parameter1, parameter2.ToString (), parameter3.ToString ());}

The call is as follows:

// Input multiple parameters for (int I = 1; I <= 20; I ++) {new Task () => {MyMethod ("My thread ", i, DateTime. now );}). start (); Thread. sleep (200 );}

The running result is as follows:

 

For multiple parameters, you can use the method of packaging multiple parameters with no parameter delegate.

2.4 Task results

To obtain the results of a Task, you must use the Task <T> to instantiate a Task when creating the Task.

T is the type of result returned after the Task is executed.

The Result can be obtained through the Result attribute of the Task instance.

System. diagnostics. stopwatch watch = System. diagnostics. stopwatch. startNew (); Task <int> myTask = new Task <int> () => {int sum = 0; for (int I = 0; I <10000; I ++) sum + = I; return sum;}); myTask. start (); Console. writeLine ("Result: {0} Time consumed: {1}", myTask. result, watch. elapsedMilliseconds );

The running result is as follows:

Use the Factory property to complete the preceding example:

// Use the Factory property to create System. diagnostics. stopwatch watchSecond = System. diagnostics. stopwatch. startNew (); Task <int> myTaskSecond = Task. factory. startNew <int> () => {int sum = 0; for (int I = 0; I <10000; I ++) sum + = I; return sum;}); Console. writeLine ("Result: {0} Time consumed: {1}", myTaskSecond. result, watchSecond. elapsedMilliseconds );

The running result is as follows:

In addition to the basic knowledge above, multithreading can be used in processing various parallel tasks and multi-core programming. For more information, see the books on multithreading.

To thoroughly learn multithreading, you need to practice and accumulate.

3. Highlights of this section:

A. This section briefly introduces the use of ThreadPool in the thread pool;

B. describes how to use a Task to create multiple threads and pass in and return results of Tast parameters.

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

Returned directory

<If it is helpful to you, remember to clickRecommendationOh, if you have any questions or errors, please contact us more>

<If you have any difficulties reading this series of articles, please read them first.. Net Object-Oriented Programming Basics>

<Reprinted statement: technology requires a spirit of sharing. You are welcome to repost the article in this blog, but please note the copyright and URL>

. NET exchange group: 467189533

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

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.