C # multi-thread Technical Summary (asynchronous ),

Source: Internet
Author: User

C # multi-thread Technical Summary (asynchronous ),

Here I will summarize the existing C # multithreading technology. One is review, and the other is convenient indexing. Some knowledge points in this article come from the Internet and are not self-created.

1. Parallel (asynchronous ):

1. In the System. Threading. Tasks namespace (TPL ):

1.1: Parallel. Invoke: executes multiple tasks in Parallel, and the main thread starts to run in Parallel.

Example:

Static void Main (string [] args) {Parallel. Invoke (new ParallelOptions () {MaxDegreeOfParallelism = 2}, Run1, Run2); Console. WriteLine ("I am the Main thread! "); Console. read ();} static void Run1 () {Console. writeLine ("I am Task 1, I am running 3 s"); Thread. sleep (1, 3000); Console. writeLine ("Task 1 execution completed first");} static void Run2 () {Console. writeLine ("I am Task 2, I am running 5 s"); Thread. sleep (1, 5000); Console. writeLine ("Task 2 execution completed first ");}

1.2: Parallel. For -- multiple tasks are iterated cyclically. Parallel Execution occurs between multiple tasks. The main thread starts to run the rolling operation only after the execution of multiple tasks in the loop iteration is completed.

Example:

Parallel. for (0, 10, (I) => {Console. writeLine ("I Am A {0} task, Thread ID: {1}", I, Thread. currentThread. managedThreadId); Thread. sleep (new Random (). next (10) * 10*500); Console. writeLine ("Thread ID: {0} execution completed", Thread. currentThread. managedThreadId );});

1.3: Parallel. ForEach: multiple tasks are iterated cyclically. Parallel Execution occurs between multiple tasks. The main thread starts to run the rolling operation only after multiple tasks of cyclic iteration are completed. Note that it has multiple overload Methods

Example:

Var bag = new ConcurrentBag <int> (); Parallel. forEach (Partitioner. create (0,100), I => {for (int m = I. item1; m <I. item2; m ++) {bag. add (m); Console. writeLine ("I Am A {0} task, Thread ID: {1}", m, Thread. currentThread. managedThreadId) ;}}); Console. writeLine ("Parallel Computing: Set: {0}", bag. count );

1.4: TAP (asynchronous Task-based editing) and use the Task class (Note: After the default Task is enabled, it will be executed in the new thread. The main thread will not wait for the Task but will continue the following execution, if you use Task. waitAll, the task will be executed only after the corresponding task is completed)

Example:

// Method 1 start var task1 = new Task () => // instantiate {Run1 () ;}); task1.Start (); // start // The second method to enable var task2 = Task. factory. startNew () => // directly create a Task and start {Run2 () ;}); // The main thread waits for the Task to be executed. waitAll (task1, task2 );

2. ParallelEnumerable class Extension Method (first convert the enumerated object to the ParallelQuery type using AsParallel, then you can use the ParallelQuery Extension Method Related to the ParallelEnumerable class)

Example:

var resultList = testList.AsParallel().Where(i=>i>=100).ToList(); Console.WriteLine("resultList Count:{0}", resultList.Count);

3. create a new Thread-after the new Thread is started, the main Thread and the created Thread are executed separately. If the main Thread needs to wait until the asynchronous Thread is executed completely, use asyncThread. join method.

Example:

Static void AsyncThreadMethod () {Console. writeLine ("I am an asynchronous execution Thread, Thread ID is: {0}", Thread. currentThread. managedThreadId);} static void AsyncThreadMethod (object state) {Console. writeLine ("I am an asynchronous execution Thread, Thread ID: {0}, status: {1}", Thread. currentThread. managedThreadId, state);} // create a Thread and execute Thread asyncThread = new Thread (new ThreadStart (AsyncThreadMethod); asyncThread. isBackground = true; asyncThread. start (); Thread asyncThread2 = new Thread (new ParameterizedThreadStart (AsyncThreadMethod); asyncThread2.IsBackground = true; asyncThread2.Start ("this is a parameter for autonomous Threads ");

4. Use ThreadPool. QueueUserWorkItem static method -- WaitCallback callback method requires that it contain an object parameter

Example:

ThreadPool. queueUserWorkItem (new WaitCallback (AsyncThreadMethod); // without parameters, the system automatically sets the state to nullThreadPool. queueUserWorkItem (new WaitCallback (AsyncThreadMethod), "This is a parameter for autonomous Threads ");

5. APM (asynchronous programming model), uses BeginInvoke and EndInvoke to Implement Asynchronous execution of the delegate Method

Example:

Func <string, string> funcDelegate = (s) => {Console. WriteLine ("I'm the Func delegate method! "); Return" delegate method parameters: "+ s ;}; // 1. no blocking asynchronous callback var aysncResult = funcDelegate. beginInvoke ("this is a parameter for autonomous Threads", new AsyncCallback (result) =>{// get the delegate object, call the EndInvoke method to obtain the running result AsyncResult _ result = (AsyncResult) result; var func = (Func <string, string>) _ result. asyncDelegate; string data = func. endInvoke (_ result); Console. writeLine (data + ", additional parameter:" + _ result. asyncState. toString () ;}, "other parameters"); // 2. the main thread is blocked so that the main thread waits for execution to complete stri Ng data2 = null; var aysncResult2 = funcDelegate. beginInvoke ("this is the parameter for autonomous threads 2", null, null); data2 = funcDelegate. endInvoke (aysncResult2); // The first blocking method while (! AysncResult2.IsCompleted) // The second blocking method {Thread. sleep (200); // Virtual Operation Console. writeLine ("main thread waiting... ");} data2 = funcDelegate. endInvoke (aysncResult2); WaitHandle [] waitHandles = new WaitHandle [] {aysncResult2.AsyncWaitHandle}; while (WaitHandle. waitAll (waitHandles, 5000) // The third blocking method {Console. writeLine ("main thread waiting... ");}

6. EAP (Event-based asynchronous programming) -- mainly used in Client Applications

Example:

// Example 1 var client = new WebClient (); client. downloadProgressChanged + = delegate (object s, DownloadProgressChangedEventArgs e) {Console. writeLine ("Download Percent: {0}", e. progressPercentage) ;}; client. downloadStringCompleted + = delegate (object s, DownloadStringCompletedEventArgs e) {Console. writeLine ("Download Content Length: {0}", e. result. length); Console. writeLine ("Download Completed! ") ;}; Client. downloadStringAsync (new Uri ("http://www.zuowenjun.cn"); // Example 2 BackgroundWorker worker = new BackgroundWorker (); worker. doWork + = (s, e) => {Console. writeLine ("Asynchronous execution... ") ;}; Worker. RunWorkerCompleted + = (s, e) =>{ Console. WriteLine (" Asynchronous execution completed... ") ;}; Worker. RunWorkerAsync ();

7. async and await keywords

Example:

Public Task <double> GetValueAsync (double num1, double num2) {return Task. run () => {for (int I = 0; I <1000000; I ++) {num1 = num1/num2 ;}return num1 ;});} public async void DisplayValue () {double result = await GetValueAsync (1234.5, 1.01); // a new thread is enabled to process the GetValueAsync task, then, all the code after the method returns // will be encapsulated as a delegate, and the System will be called when the GetValueAsync task is completed. diagnostics. debug. writeLine ("Value is:" + result);} // call DisplayValue (); // The main thread is not blocked.

Refer to the following articles:

C # comprehensive secrets-multiple threads (I)

C # comprehensive secrets-multiple threads (below)

8-day interactive parallel development series of articles

. Net basics (5) multithreading development Basics

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.