NET multithreaded programming (reprint)

Source: Internet
Author: User

The System.Threading.Tasks.Parallel class provides the three static methods of Parallel.invoke,parallel.for,parallel.foreach.

1 Parallel.Invoke

Perform each operation provided as much as possible in parallel, unless the user cancels the operation.

Method:

1) public static void Invoke (params action[] actions);

2) public static void Invoke (ParallelOptions paralleloptions,

params action[] actions);

Parameters:

ParallelOptions: An object that is used to configure the behavior of this operation.

Actions: Array of actions to perform

Abnormal:

For Method 1:

The System.ArgumentNullException:actions parameter is null.

System.aggregateexception: The exception that is thrown when any operation in the actions array throws an exception.

The System.ArgumentException:actions array contains a NULL element.

In addition to the above exception, Method 2 includes:

System.OperationCanceledException:parallelOptions set the System.Threading.CancellationToken.

System.objectdisposedexception: in paralleloptions with System.Threading.CancellationToken The associated System.Threading.CancellationTokenSource has been disposed.

Description

1) The Invoke method returns only if all actions have been completed, even if an exception occurs during execution.

2) You cannot guarantee that all actions in the actions are executed simultaneously. For example, if the action size is 4, but the number of hardware threads is 2, then the maximum number of operations running at the same time is 2.

3) operations in the actions are run in parallel, regardless of order, and if you write concurrent code related to the order of operations, you should choose a different method.

4) If you use invoke to load multiple operations, multiple operations run at different times, with the total elapsed time being the most time consuming operation, which causes many logical cores to be idle for a long time.

5) Limited parallel extensibility, which stems from the number of delegates invoked by invoke is fixed.

2 Parallel.For

Iterations may be run in parallel, and the state of the loop can be monitored and manipulated. Parallel.For has multiple overloaded methods, and some of the methods are listed below.

Method:

1) public static parallelloopresult for (int frominclusive, int toexclusive, action<int> body);

2) public static parallelloopresult for (int frominclusive, int toexclusive, action<int, parallelloopstate> body);

3) public static parallelloopresult for (int frominclusive, int toexclusive, paralleloptions paralleloptions, action< int, parallelloopstate> body);

4) public static parallelloopresult for<tlocal> (int frominclusive, int toexclusive, paralleloptions ParallelOptions, func<tlocal> localInit, Func<int, ParallelLoopState, tlocal, tlocal> body, Action< Tlocal> localfinally);

Parameters:

Frominclusive: Start index (inclusive).

Toexclusive: End index (not included).

Body: The delegate that will be called once per iteration.

ParallelOptions: An object that is used to configure the behavior of this operation.

LocalInit: A delegate that returns the initial state of local data for each task.

Localfinally: A delegate that performs a final operation on the local state of each task.

return Result:

Parallelloopresult: Contains information about the completed Loop section.

Abnormal:

The System.ArgumentNullException:body parameter is null, or the localInit parameter is null, or the localfinally parameter is null, or the paralleloptions parameter is null. System.aggregateexception: An exception that contains all the individual exceptions thrown on all threads.

For Method 3) and 4) in addition to the above exception include:

System.operationcanceledexception: Parameter System.Threading.CancellationToken is set in ParallelOptions.

System.objectdisposedexception: associated with System.Threading.CancellationToken in ParallelOptions System.Threading.CancellationTokenSource has been released.

Description

1) floating point and stepping are not supported.

2) The execution order of the iterations cannot be guaranteed.

3) If frominclusive is greater than or equal to Toexclusive, the method returns immediately without performing any iterations.

4) for the ParallelLoopState instance contained in the body parameter, its function is to interrupt the parallel loop early.

5) The result will not be returned until the iteration is complete, or the loop will remain blocked.

3 Parallel.ForEach

Method

1) public static Parallelloopresult ForEach (ienumerable<tsource> source, action<tsource> body);

2) public static Parallelloopresult foreach<tsource> (ienumerable<tsource> source, paralleloptions ParallelOptions, Action<tsource, parallelloopstate> body);

3) public static Parallelloopresult foreach<tsource> (partitioner<tsource> source, action<tsource> body);

Parameters:

Source: Data Source

Body: The delegate that will be called once per iteration.

ParallelOptions: An object that is used to configure the behavior of this operation.

return Result:

Parallelloopresult: Contains information about the completed Loop section.

Abnormal:

The System.ArgumentNullException:source parameter is null. -or-party body parameter is null.

System.aggregateexception: Contains all the individual exceptions thrown on all threads.

For Method 2) also includes:

System.operationcanceledexception: Parameter System.Threading.CancellationToken is set in ParallelOptions.

System.objectdisposedexception: associated with System.Threading.CancellationToken in ParallelOptions System.Threading.CancellationTokenSource has been released.

For 3) The included exceptions are:

The System.ArgumentNullException:source parameter is null. -or-party body parameter is null.

System.InvalidOperationException:source System.collections.concurrent.partitioner<tsource> in the partitioning program;. The SupportsDynamicPartitions property returns False. or throws an exception when any method in the source partitioner returns NULL. Or system.collections.concurrent.partitioner<tsource> in the source partition program;. The GetPartitions (System.Int32) method does not return the correct number of partitions.

Description

1) for the ParallelLoopState instance contained in the body parameter, its function is to interrupt the parallel loop early.

2) The Parallel.ForEach method does not guarantee the order of execution, and it does not always execute sequentially as the Foreach loop does.

3) for source in Method 3, its type is partitioner<tsource>. You can use the Partitioner.create method to create a partition that has several methods of reorganization:

L public static Orderablepartitioner<tuple<int, int>> Create (int frominclusive, int toexclusive);

L public static Orderablepartitioner<tuple<int, int>> Create (int frominclusive, int toexclusive, int Rangesize);

The frominclusive is the lower range (inclusive), the toexclusive is the lower range (not included), and the rangesize is the size of each child range.

The child range size created by using Partitioner is approximately three times times the default of the computer core, and when you use Rangesize to specify a range size, the child range size is the specified value.

4) The result will not be returned until the iteration is complete, or the loop will remain blocked.

4 paralleloptions

Defined:

Storage options for configuring the methods of the System.Threading.Tasks.Parallel class.

paralleloptions Properties :

1) Public CancellationToken CancellationToken {get; set;}

Gets or sets the propagation of notifications about actions that should be canceled.

2) public int maxdegreeofparallelism {get; set;}

Gets or sets the maximum degree of parallelism allowed for this paralleloptions instance.

3) Public TaskScheduler TaskScheduler {get; set;}

Gets or sets the System.Threading.Tasks.TaskScheduler associated with this System.Threading.Tasks.ParallelOptions instance

Description

1) by setting CancellationToken to cancel the parallel loop, the currently running iteration finishes executing and then throws an exception of type system.operationcanceledexception.

2) The TPL approach always attempts to utilize all available cores for best results, but it is possible that the heuristic algorithm used internally by the. NET framework has injected and used more threads than was actually needed (usually higher than the number of hardware threads, which would better support the CPU and i/ o mixed-type workloads).

The maximum degree of parallelism is typically set to less than or equal to the number of logical cores. If set to equals the number of logical cores, make sure that the execution of other programs is not affected. Set to less than the number of logical cores is to have the idle kernel to handle other urgent tasks.

Use:

1) Canceling the parallel loop from the outside of the loop

2) Specify the degree of parallelism

3) Specify a custom Task Scheduler

5 ParallelLoopState

Defined:

Enables parallel loop iterations to interact with other iterations. Instances of this class are provided to each loop by the Parallel class, and instances cannot be created in user code.

Method:

1) Break () method: Notifies the parallel loop to stop execution as soon as possible after executing the current iteration, ensuring that the low index step is complete. And you can ensure that the iteration you are performing continues to run until it is complete.

2) Stop () method: Notifies the parallel loop to stop executing as soon as possible. An iteration that has not been run cannot attempt to perform a low index iteration. There is no guarantee that all running iterations will be executed.

Purpose: exit the parallel loop early.

Description

1) You cannot use both break and stop in the same parallel loop at the same time.

2) Stop is more commonly used than break. The effect of a break statement in a parallel loop differs from that used in a serial loop. Break is used in parallel loops, where the principal method of a delegate is called at each iteration, and the principal method that exits the delegate has no effect on the execution of the parallel loop. Stop stopping the loop faster than break.

6 Parallelloopresult Structure

Defined:

The information for the parallel loop run result.

Property:

1) public bool iscompleted {get;}

True if the loop has finished running (all iterations of the loop have been executed and the loop has not received a request to end prematurely); otherwise, false.

2) public long? lowestbreakiteration {get;}

Returns an integer representing the lowest iteration from which the break statement was called

Purpose: Determines whether the parallel loop is exited prematurely when the break method or stop method is called, or all iterations are executed when the parallel loop ends.

Basis of judgment:

Conditions

IsCompleted

Run complete

! IsCompleted &&

Lowestbreakiteration==null

Terminated prematurely using the Stop statement

! IsCompleted &&

lowestbreakiteration! =null

Terminated prematurely using the break statement

7 capturing exceptions in a parallel loop

Principle:

1) Exceptions take precedence over canceling from outside the loop and using the break () method or the Stop () method to exit the parallel loop early.

2) The parallel loop body throws an unhandled exception, and the parallel loop can no longer start a new iteration.

3) By default, when an unhandled exception is thrown by an iteration, the iteration that is being executed will execute if no exception is thrown. When all iterations are executed (it is possible that other iterations also throw an exception during execution), the parallel loop throws an exception in the thread that called it.

During a parallel loop run, there may be multiple iterations that throw exceptions, so it is common to use aggregateexception to catch exceptions. AggregateException inherits from exception. To prevent certain exceptions from being caught using only aggregateexception, use aggregateexception while using exception.

8 usage Mode

8.1 Parallel.Invoke

1 public static void Demonstrateinvoke () 2 {3     //Using lambda 4     parallel.invoke (5     () = 6     {7         //specific operation 1 8     },  9     () = ten {one-to-one         //specific operation 212     });/     /Do not use LAMBDA15     parallel.invoke ( Operation1, Operation2);}17 private static void Operation1 () {     //specific operation 121}22 + private static void Operati On2 ()     226}        

8.2 Parallel.For

1 Serial loop: 2 int toexclusive = ...; 3 for (int i =0;i<=toexclusive;i++) {};4 5 corresponds to a parallel loop: 6 parallel.for (0, toexclusive+1, (i) = = 7 {8     //specific Operation 9});

8.3 Parallel.ForEach

1 General usage 2 ienumerable<string> coll = ...; 3 Parallel.ForEach (coll, (str) = 4 {5     //specific Operation 6}); 7  8 Partition-based mode 9 optimizes the number of partitions closest to the system logical cores: 10 sub-partition Range = to "pending collection size/system logical Kernel" Number "rounding +1. int logicalcores = ...; Ienumerable<string> COLLP = ...; int frominclusive = ...; int toexclusiv = ...; int rangesize = (int) ((toexclusiv-frominclusive)/logicalcores) +1;16 Parallel.ForEach (Partitioner.create ( Frominclusive, Toexclusiv, rangesize), range =>17 {for     (int i = range. Item1; I < range. ITEM2; i++)     {         //Use Set: Collection[i]21     }22});    

8.4 from the outside of the loop canceling a parallel loop

Note: An exception of type aggregateexception cannot be caught without using iscancellationrequested or throwifcancellationrequested ().

1) for Parallel.For

Using the IsCancellationRequested property

1 public static void Cancelfromexternal () 2 {3     cancellationtokensource cts = new CancellationTokenSource (); 4     //its He operates ... 5  6     //Asynchronous execution operation Method 7     Task.Factory.StartNew (() =>{operation (CTS),}); 8     //asynchronous execution of condition calculation procedure 9     Task.Factory.StartNew (() =>{10         bool condition = ...; One         -if (condition) CTS. Cancel ();     }13     //other operations ... }16-private static void operation (CancellationTokenSource CTS)-     cancellationtoken ct = cts. Token;20     paralleloptions op = new ParallelOptions {cancellationtoken = ct};21     int toexclusive = ...;     parallel.for (0, Toexclusive, op, (i) =>23     {         //other operations ...         //return only valid for the current sub         -thread if (CT). iscancellationrequested)         {return;}         //Other operation ...     ); 33}                    

Throw an exception using the throwifcancellationrequested () method

Replace the parallel loop section above with the following code:

1 parallel.for (0, Toexclusive, op, (i) =>2 {3 4     //other operations ... 5 6     Ct. Throwifcancellationrequested (); 7 8     //Other operations ... 9});

Do not use iscancellationrequested and throwifcancellationrequested () method

Remove the code that involves the iscancellationrequested and throwifcancellationrequested () methods in the Operation method

2) for Parallel.ForEach

Using the IsCancellationRequested property

1 public static void Cancelfromexternal () 2 {3     //same 1) in Cancelfromexternal Method 4} 5  6 private static void operation (C Ancellationtokensource CTS) 7 {8     cancellationtoken ct = cts. Token; 9     paralleloptions op = new ParallelOptions {cancellationtoken = ct};10     ienumerable<string> coll = new List <string> {"str1", "str2"};11     Parallel.ForEach (Coll, op, (str, loopstate) =>12     {         //other operations ...       //return only valid for the current sub       -thread, if (Ct. iscancellationrequested)       {return;}       Other operations ...   ); 21}

Throw an exception using the throwifcancellationrequested () method

In the Operation method:

if (Ct. iscancellationrequested)

{return;}

To be replaced by:

Ct. Throwifcancellationrequested ();

Do not use iscancellationrequested and throwifcancellationrequested () method

Remove the code that involves the iscancellationrequested and throwifcancellationrequested () methods in the Operation method

8.5 specifying the degree of parallelism

1 int maxdegreeofparallelism = environment.processorcount-1;2 paralleloptions op = new ParallelOptions {MaxDegreeOfPara Llelism =     maxdegreeofparallelism};3 ienumerable<string> coll = new list<string> {};4 Parallel.ForEach ( Coll, op, (str) =>5 {6     //specific Operation 7});

8.6 Exiting the parallel loop early

1) for Parallel.For

1 int toexclusive = 10; 2 parallel.for (0, toexclusive, (I, loopstate) and 3 {4     //other operations ... 5     //Calculate condition 6     bool condition = ...; 7     if (condition) 8     {9         loopstate.break ();// or use LOOPSTATE.STOP10         return;11     }12     //other Operation 14});    

2) for Parallel.ForEach

1 ienumerable<string> coll = new list<string> {"str1", "str2"}; 2 Parallel.ForEach (coll, (str, loopstate) = 3 {4     //other operations ... 5  6     //Calculate condition 7     bool condition = ...; 8     if (condition) 9     {ten         loopstate.break ();// or use loopstate.stop11         return;12     }13     //Other Operations 15 16});

9 Exception Handling mode

Basic form

You can omit catch (Exception e) Parts When you are sure that you can catch all the exceptions using AggregateException.

1 Try 2 {3     //do something 4} 5 catch (AggregateException e) 6 {7     Foreach (Exception ex in E.innerexceptions) 8
   {9         //do something10     }11}12 catch (Exception e)-{//do something15     }

NET multithreaded programming (reprint)

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.