C # Study Notes 13,

Source: Internet
Author: User

C # Study Notes 13,

1.Task Overview: a Task is an abstraction of the operating system threads to enable the thread pool to efficiently manage thread allocation and collection. The underlying thread used by a Task is a shared resource, tasks need to collaborate with each other and return the threads in time to meet other requests with the same shared resources (threads.

2.Task. AsyncState: gets the State object provided when a Task is created. If not, it is null. If the State object changes within the task, the AsyncState data is also the State object after the change. You can view the code of the ThreadApply. TaskAsyncState () method.

3.Task. ContinueWith (): it is used to link tasks. After the parent Task is completed, subsequent tasks are executed immediately. If the ContinueWith () method is called multiple times on the instance of the parent task, after the parent task is completed, the added subsequent tasks are executed in parallel. Of course, you can specify based on TaskContinuationOptions enumeration to execute subsequent tasks based on the execution of the parent task.

4.Task exceptions: unhandled exceptions generated during Task execution will be disabled until a Task is called to complete (Task) members, such as Wait (), Result, WaitAll (), WaitAny (), the above members will cause the unhandled exception during the task execution. You can view the code TreadApply. TaskException ().

5.Task exception 2: To handle unhandled exceptions without using try/catch blocks, another method is to use the ContinueWith () task and use the Task parameters entrusted by ContinueWith, the Exception attribute of the parent task can be evaluated. You can view the code TreadApply. taskException2 ().

6.Task cancellation: You can view the code ThreadApply. the CancellationTokenSource class must be used for the TaskCancellationToken () method. the Cancel () method is called from CancellationTokenSource. set the IsCancellationRequested attribute on all cancel signs of Token replication. Note the following two points,

(1) Cancel flag: CancellationToken (instead of CancellationTokenSource) will be evaluated in an asynchronous task. CancellationToken looks similar to CancellationTokenSource. However, CancellationToken is used to monitor and respond to a cancellation request, while CancellationTokenSource is used to cancel the task itself.

(2) Copied: CancellationToken is a struct. Therefore, calling CancellationTokenSource. Token creates a copy of the flag. In this way, all instances that cancel the flag are thread-safe.

7.Long-running tasks: If a developer knows that a Task needs to run for a long time and will "Occupy" the underlying thread resources for a long time, the developer should tell the thread pool sharing thread not to return the Task too quickly. In this way, the thread pool is more likely to create a dedicated thread for the task (instead of allocating one of the Sharing threads). Therefore, when calling StartNew (), you must use the TaskCreationOption. LongRunning option.

8.Parallel iteration: two Parallel iterations are added in. net4.0, namely Parallel. For () and Parallel. Foreach (). The API determines how many threads are executed simultaneously, which is the most efficient. You can view the code of the ThreadApply. ParallelFor () and ThreadApply. ParallelForeach () methods.

9.Parallel Exception Handling: When parallel processing occurs, multiple exceptions may occur in parallel content, so the exception information will be classified into the aggresponexception exception type, it is an exception that contains multiple internal exceptions. The System. Threading. Task namespace uses System. aggresponexception to group unprocessed exceptions, because multiple exceptions may occur in parallel operations. For example, ThreadApply. ParallelForeach () code list.

10.Cancel a parallel loop: a Task requires an explicit call to block (its calling thread is always waiting) until it completes. Although the parallel loop is different from the Task, it executes iterations in Parallel, but it still blocks (its calling thread, and always waits) to the entire Parallel. for () or Parallel. the ForEach () loop ends. To cancel a parallel loop, the thread that calls the cancel request cannot be the thread that is executing the parallel loop. For example, the Code ThreadApply. CancelParallelForeach () list.

11.Parallel iteration interruption: similar to the standard for loop, Parallel loop also supports ParallelLoopState. Break () to exit the loop and cancel the concept of further iteration. However, in the context of parallel execution, the interrupted loop means that the new iteration after the interrupted iteration should not start, and the current iteration will continue to run until it is completed. You can view the parallel For ()/ForEach () the ParallelLoopResult object returned by the method (which contains the IsCompleted and LowestBreakIteration attributes ).

12.Parallel Linq query: The functions of parallel Linq are all in System. linq. in the ParallelEnumerable class, the method form of this class is as follows. linq. the methods of the Enumerable class are basically the same. The ParallelEnumerable class has an extension method for converting IEnumerable <T> type into a parallel processing type, that is, IEnumerable <T>. asParallel (). The set can be processed in parallel only after this conversion is executed.

13.Parallel Linq exceptions: Like parallel For and Foreach, PLinq operations may return multiple exceptions For the same reason (different iterations are executed simultaneously). Fortunately, the same is true for exception capturing. PLinq exceptions can be accessed through the InnerException attribute of aggresponexception. Therefore, a Plinq query is encapsulated into a try/catch Block and an exception of the aggresponexception type is caught, you can handle the unprocessed exceptions in each iteration.

14.Cancel PLinq query: similar to a parallel loop, the canceled PLinq query will trigger an OperationCanceledException. In addition, the PLinq query will block the call thread until the query is completed. Therefore, we should package parallel Linq in the Task. Before canceling the PLinq function, you need to execute the WithCancellation () method on the parallel set, such as the Code TreadApply. CancelParallelLinq () list.

15.Asynchronous class usage instructions: when selecting the asynchronous class to be used, tasks, ThreadPool, and threads are selected in the order of priority from high to low. In other words, TPL is preferred. If not, ThreadPool is used. If not, Thread is used.

16.UnhandledException of AppDomain: to register a callback method to receive unhandled exception notifications in the main application, you only need to register the UnhandledException event in the application domain. You can view ThreadApply. the AppDomainException () code list. Any unhandled exceptions on the threads in the application domain (including the main thread) will trigger the UnhandledException callback. This is only a notification mechanism, instead of capturing and handling exceptions to enable the application to continue running. After the event occurs, the application exits.

Public class ThreadApply {public void TaskCreate () {int times = 1000; Task task = new Task () => {for (int I = 0; I <times; I ++) {Console. write ("-") ;}}); task. start (); for (int I = 0; I <times; I ++) {Console. write (". ");} task. wait ();} public void TaskStaticCreate () {Task <string> task = Task. factory. startNew () => {Thread. sleep (100); return "main god" ;}); foreach (char busySymbol in Utility. B UsySymbols () {if (task. isCompleted) {Console. write ('\ B'); break;} Console. write (busySymbol);} Console. writeLine (); Console. writeLine (task. result); Console. writeLine (task. status); Trace. assert (task. isCompleted);} public void TaskAsyncState () {Man man = new Man () {Name = "", Age = 1}; Task task = Task. factory. startNew (_ man) => {Man tempMan = (Man) _ man; Console. writeLine ("before execution {0}", tempMa N); tempMan. name = "Titans"; tempMan. age + = 10; Console. writeLine ("{0} after execution", tempMan) ;}, man); task. wait (); Console. writeLine ("original {0}, asynchronous {1}", man, task. asyncState);} public void TaskContinueWith () {Task <string> task = Task <string>. factory. startNew () => {Console. writeLine (""); Thread. sleep (200); return "Red Star" ;}); Task faultedTask = task. continueWith (antecedentTask) => {Trace. assert (antecedentTa Sk. isFaulted); Console. writeLine ("Task State: Faulted") ;}, TaskContinuationOptions. onlyOnFaulted); Task cancelTask = task. continueWith (antecedentTask) => {Trace. assert (antecedentTask. isCanceled); Console. writeLine ("Task State: Canceled") ;}, TaskContinuationOptions. onlyOnCanceled); Task completedTask = task. continueWith (antecedentTask) => {Trace. assert (antecedentTask. isCompleted); Console. wri TeLine ("Task Result: {0}", antecedentTask. result); Console. writeLine ("Task State: Completed") ;}, TaskContinuationOptions. onlyOnRanToCompletion); completedTask. wait (); // This code can be used only to prevent the console from closing.} public void TaskException () {// The code here demonstrates the unprocessed framework, how to return unprocessed exceptions of a Task to the main thread. Note that the exception data type is the exception set aggresponexception, and the task Task is a Task. factory. startNew () =>{ throw new ApplicationException () ;}); try {task. wait ();} catch (Aggresponexception ex) {foreach (Exception item in ex. innerExceptions) {Console. writeLine ("error: {0}", item. message) ;}} public void TaskException2 () {/* Task task = Task. factory. startNew () =>{ throw new ApplicationException () ;}); Task faultedTask = task. continueWith (antecedentTask => {Console. writeLine ("parent task execution failed");}, TaskContinuationOptions. onlyOnFaulted); faultedTask. wait (); if (task. IsFaulted) {Console. writeLine ("Error: {0}", task. exception. message); // The exception type of the task is aggresponexception} */Task task = Task. factory. startNew () =>{ throw new ApplicationException () ;}); Task faultedTask = task. continueWith (antecedentTask => {foreach (var item in antecedentTask. exception. innerExceptions) {Console. writeLine ("Error: {0}", item. message);} Console. writeLine ("parent task execution failed");}, TaskContinuat IonOptions. onlyOnFaulted); faultedTask. wait ();} public void TaskCancellationToken () {string stars = "*". padRight (50, '*'); Console. writeLine ("Push Enter to exit. "); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource (); Task task = Task. factory. startNew () => Utility. writeNaturalNumber (cancellationTokenSource. token), cancellationTokenSource. token); Thread. sleep (2000); C Onsole. writeLine (); cancellationTokenSource. cancel (); Console. writeLine (stars); task. wait (); Console. writeLine ("Task Status: {0}", task. status); // The task is canceled normally, so the task Status is RanToCompletion. If the status is Canceled, but the CancellationToken. ThrowIfCancellationRequested () method is used, an exception is reported.} Public void ParallelFor () {Parallel. for (0,100, (I) => {Console. writeLine ("No. {0} Times, threadId = {1}", I, Thread. currentThread. managedThreadId) ;}) ;}public void ParallelForeach () {IEnumerable <string> files = Directory. getFiles ("D :\\","*. txt ", SearchOption. allDirectories); try {Parallel. forEach (files, (fileName) =>{// Encrypt (fileName) ;});} catch (aggresponexception ex) {foreach (var item in Ex. innerExceptions) {Console. writeLine (item. message) ;}} public void CancelParallelForeach () {IEnumerable <string> files = Directory. getFiles ("D :\\","*. txt ", SearchOption. allDirectories); CancellationTokenSource cts = new CancellationTokenSource (); ParallelOptions parallelOptions = new ParallelOptions () {CancellationToken = cts. token}; cts. token. register () => Console. writeLine ("Cancelling. .. "); Console. writeLine ("Push Enter to exit. "); Task task = Task. factory. startNew () => {// note that, internally, the parallel loop condition uses the IsCancellationRequested attribute to prevent the start of a new iteration that has not yet started. Parallel. forEach (files, parallelOptions, (fileName, loopState) =>{// Encrypt (fileName) ;}); Console. readLine (); cts. cancel (); Console. writeLine ("--------- split line ----------"); task. wait ();} public void ParalleEncrypt (List <string> data) {ParallelQuery <string> result = data. asParallel (). select (item => Utility. encrypt (item);} public void CancelParallelLinq () {IEnumerable <int> data = Enumerable. R Ange (0, 10000); CancellationTokenSource cts = new CancellationTokenSource (); Console. writeLine ("Push Enter to exit. "); Task task = Task. factory. startNew () => {data. asParallel (). withCancellation (cts. token ). select (item => {Thread. sleep (100); // return item> 1;});}, cts. token);/* besides being passed to WithCancellation (), CancellationToken must also be passed as the second parameter of StartNew (), which causes Task. wait () raises an aggresponexception, whose Inne The rException attribute is set to a TaskCanceledAException */Console. readLine (); cts. cancel (); Console. writeLine ("------------ split line ----------------"); try {task. wait ();} catch (aggresponexception ex) {foreach (Exception item in ex. innerExceptions) {Console. writeLine (item. message) ;}} public void AppDomainException () {try {AppDomain. currentDomain. unhandledException + = Utility. onUnHandledException; ThreadPool. QueueUserWorkItem (state =>{ throw new Exception ("Unforgivable") ;}); Thread. sleep (1, 3000); Console. writeLine ("Still Running... ");} finally {Console. writeLine ("Exiting .... ") ;}} public class Man {public string Name {get; set;} public int Age {get; set;} public override string ToString () {return string. format ("Name: {0}, Age: {1}", Name, Age) ;}} public class Utility {public static IEnumerable <char> B UsySymbols () {string busySymbols = @ "-\ |/"; int next = 0; while (true) {yield return busySymbols [next]; next = ++ next % busySymbols. length; yield return '\ B ';}} /// <summary> /// output natural number /// </summary> /// <param name = "cancellationToken"> unmark </param> public static void WriteNaturalNumber (cancellationToken cancellationToken) {int num = 0; while (! CancellationToken. isCancellationRequested) {Thread. sleep (1, 100); Console. write ("{0},", num ++) ;}} public static string Encrypt (string text) {throw new NotImplementedException () ;}public static void OnUnHandledException (object sender, unhandledExceptionEventArgs e) {Exception exception = (Exception) e. exceptionObject; Console. writeLine ("Error {0 }:{ 1} --> {2}", exception. getType (). name, exception. message, exception. innerException. message );}}
View Code

-------------- The above content is organized according to "C # the third edition of the essence theory"

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.