Learning books: <c# essence >
1--c#5.0 is recommended for use with the TPL (task Parallel libray tasks Parallel Library) and PLINQ (Parallel LINQ, parallel LINQ).
Followed by tap (task-based Asynchronous Pattern, task-based Asynchronous Pattern).
--use AggregateException to handle unhandled exceptions on a task.
--Cancel the task. CancellationToken
--async modifies the method, returning a task. Task.wait (100) can block the scene. The Async method is executed within the await initiation thread.
==> the first part, 5.0 recommended ways to use threads.
2--learned how to use threads such as task synchronization:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespacetask1{classProgram {Const int_total =99999; Static Long_count =0; ReadOnly Static Object_sync =NewObject (); Static voidMain (string[] args) { //Task task = Task.run (() =>decrement ()); //for (int i = 0; i < _total; i++)//{ //_count++; //} //task. Wait (); //Console.WriteLine ("Count = {0}", _count); //Countasync (); //int x = 0; //parallel.for (0, 999999, i =// { //x + +; //x--; // }); //Console.WriteLine ("Count = {0}", x);Task task = Task.run (() = =decrement ()); for(inti =0; i < _total; i++) { BOOLLockTaken =false; Try{monitor.enter (_sync,refLockTaken); _count++; } finally { if(LockTaken) {monitor.enter (_sync); }}} task. Wait (); Console.WriteLine ("Count = {0}", _count); Console.readkey (); } Public Static Async voidCountasync () {Task Task= Task.run (() =decrement ()); for(inti =0; i < _total; i++) {_count++; } awaittask; Console.WriteLine ("Count = {0}", _count); } Static voidDecrement () { for(inti =0; i < _total; i++) { BOOLLockTaken =false; Try{monitor.enter (_sync,refLockTaken); _count--; } finally { if(LockTaken) {monitor.exit (_sync); } } } } }}
==> 第二部分.
Multithreading patterns prior to TPL and c#5.0
1. Calling APM#regionString URL="www.baidu.com"; if(args. Length >0) {URL= args[0]; } Console.WriteLine (URL); WebRequest WebRequest=webrequest.create (URL); IAsyncResult AsyncResult= Webrequest.begingetresponse (NULL,NULL); while(!asyncresult.asyncwaithandle.waitone ( -) {Console.Write ("."); } WebResponse Response=Webrequest.endgetresponse (AsyncResult); using(StreamReader reader =NewStreamReader (response. GetResponseStream ())) {intLength =Reader. ReadToEnd (). Length; Console.WriteLine (length); }
2--Complex band State operation
1--cps continuous invocation style. The Fire-and-forget mode. The EndXxx method is called after the direct re-beginxxx method is reduced.
Code that executes at the end of the "Enlist" asynchronous method through CPS.
3--passing state between APM methods
You can complete the delegate beginxxx call via Lambda.
c#5.0 is recommended for use with the TPL (task Parallel libray tasks Parallel Library) and PLINQ (Parallel LINQ, parallel LINQ). Followed by tap (task-based Asynchronous Pattern, task-based Asynchronous Pattern)