. NET parallel implementation methods (1). net parallel

Source: Internet
Author: User

. NET parallel implementation methods (1). net parallel

I haven't updated it for a long time. Today I will write an article, which is the beginning of the "synchronization and Asynchronization" series. Come on, stick to it (PS: getting lazy ).

 

I. Thread

Thread can be used to directly create and control threads. In my cognition, it is the oldest technology. The example is no longer written because it is out.

Ii. ThreadPool

Thread creation and destruction consume a lot of resources. To improve performance and introduce thread pools, that is, ThreadPool, ThreadPool can implicitly create and allocate threads.

The following are some notes from MSDN:

The thread pool provides new working threads or I/O completion threads as needed until they reach the minimum value for each category. When the minimum value is reached, the thread pool can create more threads in this category or wait for some tasks to complete. Starting from. NET Framework 4, the thread pool creates and destroys working threads to optimize throughput. The throughput is defined as the number of tasks completed per unit of time. When there are too few threads, you may not be able to make better use of available resources, but too many threads may aggravate resource contention.

When ThreadPool is directly applied, there are two application scenarios:

1. Run the methods that require asynchronous execution into the queue. When there are available threads, run the methods that are queued.
// In this application scenario, ThreadPool provides the following two methods: // public static bool QueueUserWorkItem (WaitCallback callBack); // public static bool QueueUserWorkItem (WaitCallback callBack, object state ); // WaitCallback is delegate, an object-type input parameter with no return value. // Public delegate void WaitCallback (object state); base. setTip (nameof (ThreadPool. queueUserWorkItem); ThreadPool. queueUserWorkItem (state) => {this. setTip ("waiting for one second"); Thread. sleep (1000); this. setTip ("task execution completed ");});

 

2. register the WaitHandle object and trigger the callback function when it receives the signal or times out.
// In this application scenario, ThreadPool provides four methods for overloading, in my opinion, the following overload form is the most intuitive // public static RegisteredWaitHandle RegisterWaitForSingleObject (// WaitHandle waitObject, WaitOrTimerCallback callBack, object state, long wait, bool executeOnlyOnce ); // WaitHandle is the abstract base class of the type to wait for the signal. It will be described in detail in subsequent articles. // WaitOrTimerCallback is the callback function delegate // public delegate void WaitOrTimerCallback (object state, bool timedOut ); // The state parameter is the input parameter of the callback function // The millisecondsTimeOutInterval parameter is the timer timeout period.-1 indicates that the timer never times out and waits. // You may have questions about this parameter and the first time you come into contact with it. How can this problem be solved? // Because the signal can be repeatedly received multiple times, the timer will re-timer every time it receives the signal or times out, so it has the meaning of the cycle. // ExecuteOnlyOnce. "True" indicates that the task is executed only once. "False" means to wait until the signal object is canceled. Otherwise, the callback function is triggered as long as the signal is received or timed out. Base. setTip (nameof (ThreadPool. registerWaitForSingleObject); ThreadPool. registerWaitForSingleObject (this. waitObject, (state, timeout) => {this. setTip ("++ wait for the object to receive the signal ++") ;}, null,-1, false); ThreadPool. queueUserWorkItem (state) => {this. setTip ("waiting for one second"); Thread. sleep (1000); this. setTip ("waiting for the object to send a signal"); this. waitObject. set (); this. setTip ("Wait 5 seconds"); Thread. sleep (5000); this. setTip ("waiting for the object to send a signal"); this. waitObject. set ();});

 

3. Delegate. BeginInvoke

Delegate. BeginInvoke indirectly calls the method represented by the thread pool, obtains an available thread from the thread pool, and executes the function pointer pointed to by the current Delegate.

        [Tag("Delegate.BeginInvoke")]        private void Demo3()        {            this.txtTip.SetTip("UI, Id:" + Thread.CurrentThread.ManagedThreadId);            Action action = new Action(this.DelegateTest);            action.BeginInvoke(null, null);            action.BeginInvoke(null, null);                                }        private void DelegateTest()        {            int id = Thread.CurrentThread.ManagedThreadId;            this.Dispatcher.Invoke(() =>            {                this.txtTip.SetTip("BeginInvoke, Id:" + id);            });        }


Through Thread. CurrentThread. ManagedThreadId, We can Indirectly prove that BeginInvoke is actually executed in different threads.

Of course, it corresponds to a series of Begin... End... method pairs, which are part of the asynchronous programming model of the IAsyncResult series.


In the asynchronous programming model of the IAsyncResult series, for the Demo of passing parameters and obtaining return values, see:

[Tag ("Delegate. beginInvoke has parameters and return values ")] private void Demo4 () {Func <string, string> func = new Func <string, string> (this. delegateTest2); this.txt Tip. setTip ("input parameter 123"); func. beginInvoke ("123", new AsyncCallback (System. IAsyncResult result) =>{ Func <string, string> tmp = result. asyncState as Func <string, string>; if (tmp! = Null) {string returnResult = tmp. endInvoke (result); this. dispatcher. invoke () => {this.txt Tip. setTip ("function callback Result:" + returnResult) ;}}}), func) ;}private string DelegateTest2 (string args) {return args + ": return args ";}

 

Iv. Task

Task is added in. NET 4.0 and is a Task-based Asynchronous model. It is a re-encapsulation of the thread pool, making it easier to create a variety of task combinations, such as sequential continuation tasks, parent and child tasks. The task priority can also be easily controlled in a coarse-grained manner.

1) methods advocated in Task. NET 4.0

The constructor is made public for the Task. However, Microsoft does not recommend that you use the Task constructor to instantiate an object. Instead, you can use Task. Factory. StartNew ();

The remarks in MSDN are as follows:
For performance reasons, TaskFactory's StartNew method shocould be the preferred mechanic for creating and scheduling computational tasks,
But for scenarios where creation and scheduling must be separated, the constructors may be used,
And the task's Start method may then be used to schedule the task for execution at a later time.
The Task class also provides constructors that initialize tasks but do not plan to execute tasks. For performance considerations, the StartNew method of TaskFactory should be the preferred mechanism for creating and planning computing tasks,
However, if the creation and schedule must be separated, you can use the constructor, and then you can use the Start method of the task to schedule the task to be executed later.

Task. factory. startNew () => {base. setTip ("Task. factory. startNew (a parameter )");}). continueWith (t) => {base. setTip (t. id. toString (); base. setTip (t. creationOptions. toString ());}). continueWith (t) => {base. setTip (t. id. toString (); base. setTip (t. creationOptions. toString ());});

// Task. Factory. StartNew provides up to 16 overload functions.
// Task. Factory. StartNew <TTask> is an asynchronous Task with a returned value.

// Take the most complex overload as an example to describe its parameters one by one
// Public Task <TResult> StartNew <TResult> (Func <object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler );

Function: callback function. I don't think it is necessary to explain it.
State: input parameter of the callback function
CancellationToken: Used to cancel a Task (detailed description will be provided later)
TaskCreationOptions: Specifies the flag of the optional actions that can be controlled for task creation and execution (this will be detailed in the future)
TaskScheduler: An Instance TaskScheduler class represents a task scheduler. This value is generally set to TaskScheduler. Default.

That is to say:
Task. Factory. StartNew () => {});
And
Task. Factory. StartNew () =>{}, CancellationToken. None, TaskCreationOptions. None, TaskScheduler. Default );
The two methods have the same effect.

If you want to control tasks more precisely, you can use other overload methods, and pass different parameters to achieve the expected purpose.

 

2) The Task is initialized but not scheduled to be executed.

As mentioned above, a Task provides constructor and initialization tasks, but does not plan execution.
Let's take a look at the constructor of the Task, or take the most complex as an example:
Public Task (Func <object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions );
Compared with Task. Factory. StartNew, TaskScheduler is missing. In terms of performance, MSDN prompts that the latter will be better.

Base. setTip ("initialization Task"); task Task = new task () => {base. setTip ("scheduled task execution started"); base. setTip ("task sleep for 5 seconds"); Thread. sleep (1, 5000); base. setTip ("Task execution completed") ;}); // to ensure real-time UI updates, code execution results are displayed, and code is executed asynchronously. factory. startNew () => {base. setTip ("sleep for two seconds"); Thread. sleep (1, 2000); base. setTip ("include the task in the Execution Plan"); task. start (); base. setTip ("waiting for Task execution to complete"); task. wait (); // The Wait method waits for the Task to be executed. setTip ("Task completed ");});

 

Another point is to emphasize that Task. Start () only includes the Task in the execution plan. When the Task is executed, it depends on when there are available threads in the thread pool.
The same is true for Task. Factory. StartNew.

 

Well, the introduction of the Task class, so far, will be detailed later: this powerful Task class also has many things worth exploring.

This article has come to an end.

Appendix, Demo: http://files.cnblogs.com/files/08shiyan/ParallelDemo.zip

 

See more: Casual guide: synchronous and asynchronous


(To be continued ...)

 

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.