1. Overview
This chapter is mainly about. net4.5 how to implement multithreading and asynchronous processing related content.
2. Main content
2.1 Understanding Threads
① using the Thread class
PublicStaticclassProgram { PublicStaticvoidThreadmethod () { for(inti =0; I <Ten; i++{Console.WriteLine ("ThreadProc: {0} ", i); Thread.Sleep (0); } } PublicStaticvoidMain () {Thread T=NewThread (NewThreadStart (Threadmethod)); T.start (); for(inti =0; I <4; i++{Console.WriteLine ("Main thread:do some work."); Thread.Sleep (0); } t.join (); } }
The call to the *thread.join () method is to notify the main thread to wait until another thread finishes executing.
*thread.sleep (0) is the token that the current thread's state is complete so that the system can switch to another thread immediately.
② if the IsBackground property of a thread is set to True, the main program will not consider whether the thread is still executing before exiting.
③ uses the Parameterizedthreadstart delegate to pass data through the Start method of the thread.
④ marks a property with the ThreadStatic Attribute, and each thread that uses the property obtains a copy of the property.
⑤ uses the Threadlocal<t> class, you can define thread-local data and initialize it separately for each thread.
Public Static classprogram{ Public Staticthreadlocal<int> _field =Newtheadlocal<int> (() = { returnThread.CurrentThread.ManagedThreadId; }); Public Static voidMain () {NewThread (() = { for(intx=0; x < _field.value; X + +) Console.WriteLine ("Thread A: {0}", x); }). Start (); NewThread (() = { for(intx=0; x < _field.value; X + +) Console.WriteLine ("Thread B: {0}", x); }). Start (); Console.readkey (); }}
⑥ thread Pool
Provides management and reuse of threads. The Web server receives the request, which is a typical example of using a thread pool.
2.2 Using Task
Using the task class, you can know the completion state of a thread and receive a return value.
① uses the ContinueWith method to perform subsequent tasks after the task is completed.
task<intreturn, Console.WriteLine ("Canceled } ,= = {Console.WriteLine ("Faulted");}, taskcontinationoptions.onlyonfaulted);
②task can also nest subtasks.
③taskfactory can manage tasks in bulk.
2.3 Using the Parallel class
The parallel class has a pair of static methods for, foreach, and Invoke methods that you can use to implement parallel tasks.
Parallel.For (0, i = { thread.sleep (+); }); var numbers = Enumerable.range (0+ = { Thread.Sleep ( ();});
Use ParallelLoopState to jump out of the Loop (break ()) or terminate the program (Stop ());
2.4 Using Async and await
These two keywords are used to simplify asynchronous code logic.
With the async notation, you have the ability to divide a specified part into multiple threads to execute. Specify which parts to mark with the await keyword.
public static async task<string > Downloadcontent () { using ( HttpClient client = new HttpClient ()) {string result = await client. Getstringasync ( " ); return result; }}
When UI interaction is not required, you can call the Configureawait method to disable SynchronizationContext for a better experience.
* The method for async is marked with an await.
* The method of async is marked, do not return void. (except for async events)
2.5 using Parallel Language Integrated Query (PLINQ)
With PLINQ, you can convert a sequential query into a parallel version.
var numbers = Enumerable.range (0100000000); var parallelresult = numbers. AsParallel () 20) . ToArray ();
With the asordered operation, the results are guaranteed to be orderly.
The. NET Framework concentrates the exceptions in the parallel process into aggregateexception.
2.6 Using parallel collections (concurrent collections)
The. NET Framework provides a number of thread-safe collections:
①blockingcollection<t>
When you delete data, you block the program and add more data faster.
You can use the CompleteAdding method to notify other blocked threads.
Public Static voidMain () {BlockingCollection<string> col =Newblockingcollection<string>(); Task Read= Task.run (() = { foreach(stringVinchCol. GetConsumingEnumerable ()) Console.WriteLine (v); }); Task Write= Task.run (() = { while(true) { strings =Console.ReadLine (); if(string. Isnullorwhitespace (s)) Break; Col. ADD (s); } }); Write.wait ();}
②concurrentbag<t>
Supports concurrency with replicas. Disordered.
The Trypeek method is not very useful in multi-threading. The data may have been modified in the peek process.
concurrentbag<intnew concurrentbag<int>= { bag. ADD ($); Thread.Sleep (+); Bag. ADD (+ ={ foreach(int in Bag) Console.WriteLine (i);}). Wait ();
* The above program only prints 42. Because the print program has finished executing when you add 21 to bag.
③concurrentqueue<t> and Concurrentstack<t>
is also implemented in snapshot mode.
④concurrentdictionary
varDict =Newconcurrentdictionary<string,int>();if(Dict. TryAdd ("K1", the)) Console.WriteLine ("Added");if(Dict. Tryupdate ("K1", +, the)) Console.WriteLine ("updated to +");d ict["K1"] = the;//Overwhrite uncondictionallyintR1 = Dict. AddOrUpdate ("K1",3, (s, i) = = i *2);intr2 = Dict. Getoradd ("K2",3);
3. Summary
① can treat each thread as a CPU-exclusive program.
② recommends using ThreadPool to manage threads.
③task is the encapsulation of an execution logic. Recommended for use in multithreaded code.
④paralle is used in parallel operations in code.
⑤plinq is an extension of LINQ for parallel queries.
⑥ with async and await, you can write asynchronous code in a synchronous form.
⑦ parallel collections can be thread-safe for use in multithreaded environments.
Chapter One implementation of the management program flow multithreading and asynchronous processing