Big talk asynchronous and parallel (2), big talk Asynchronous Parallel

Source: Internet
Author: User

Big talk asynchronous and parallel (2), big talk Asynchronous Parallel

Next, the previous article continued to talk about Asynchronization and parallelism.

Parallelism comes from the implementation of the thread method, and asynchronous is not necessarily. This sentence fainted a large programmer.

First, multithreading order is an asynchronous method. The two aim is to keep the main thread responding to user operations in real time, such as clicking, dragging, and inputting characters. It makes the main program seem to be waiting for the user to respond in real time, but there are several things in the background on its own. Resources can be divided into two categories: hardware Asynchronization and CPU Asynchronization.

Asynchronous hardware features: the operations that need to be performed in the background are dumped to the underlying hardware for execution,Does not occupy threads and CPU resources. Therefore, not all Asynchronization occupies the thread.

There are probably the following types of hardware asynchronous classes.

Application Scope

Supports asynchronous MethodsAPI

Web Access

HttpClient, SyndicationClient

Process files

StorageFile, StreamWriter, StreamReader, XmlReader

Use Image Processing

MediaCapture, BitmapEncoder, BitmapDecoder

WCF Programming

Synchronous and asynchronous operations

And socket Processing

Socket

 

Common asynchronous methods and methods of CPU

1. Independent thread-ThreadStart

Generally, it is necessary for a relatively short task that does not stop other threads from processing multiple threads and does not need to execute any specific Scheduling for these tasks, using the ThreadPool class is the simplest way. However, there are multiple reasons to create your own thread:

  • If you want to give a task a specific priority.

  • If you have tasks that may run for a long time (and thus stop other tasks.

  • If you want to place threads in a single thread unit (allThreadPoolThreads are all in multi-threaded units ).

  • If you need a stable identifier associated with this thread. For example, you should use a dedicated thread to stop the thread and discover it by name.

  • If you need to run the background thread that interacts with the user interface,. NET Framework 2.0 provides the BackgroundWorker component, which can use events to communicate with cross-thread messages of user interface threads.

2. ThreadPool-ThreadPool.QueueUserWorkItem (M ())

3. Tasks: Common Tasks and associated tasks (Task <T>. ContinueWith (...)) , Parent and child tasks, and task Factory (tasktacloud <TResult>)

4. Parallel static class --- System. Threading. Tasks. Parallel. (...) System. Threading. Tasks. Parallel. ForEach (...) Parallel. Invoke () => Sort ());

5. PLINQ

6. Timer

This is just a simple explanation of basic knowledge. If you are not sure, the following articles will be explained one by one.

Certificate -------------------------------------------------------------------------------------------------------------------------------------------------------------------

Thread class)

In addition to using a delegate to create a thread, you can also use the thread class to create a thread.

        static void Main(string[] args)        {            Thread t = new Thread(ThreadMain);            t.Start();            Console.WriteLine("This ia a mian thread.");        }        static void ThreadMain()        {            Console.WriteLine("Running in a thread.");        }

Simplify the above Code

 static void Main(string[] args)        {            new Thread(() =>            Console.WriteLine("Running in a thread.")        ).Start();                      Console.WriteLine("This ia a mian thread.");        }

Again, I witnessed the power of lambda expressions and anonymous methods.

In the preceding simple Thread class, a Thread is created and started. The default Thread class is IsBackground = false, that is, it is the foreground Thread.

Speaking of the foreground thread and background thread, the previous article mentioned that the background process will also stop when the current process is stopped. The background process was tested in the mian main thread and must be closed or ended, not too clear

Now with the Thread class, the following example will enable the test of the non-Lazy main Thread.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ConsoleApplication2{    class Program    {        static void Main(string[] args)        {            DateTime now = DateTime.Now;            Thread t1 = new Thread(() =>            {                Console.WriteLine("Running in a thread t1.");                Func<decimal, int, decimal> f = (money, ms) =>                {                    Console.WriteLine("SaveBankAccountPersonA thread started! current run at threadID:" + Thread.CurrentThread.ManagedThreadId);                    Console.WriteLine("SaveBankAccountPersonA thread IsBackground " + Thread.CurrentThread.IsBackground);                    Thread.Sleep(ms);                    Console.WriteLine("SaveBankAccountPersonA thread completed!");                    return ++money;                };                var ar = f.BeginInvoke(1, 200, (r) =>                {                    if (r == null)                    {                        throw new ArgumentNullException("r");                    }                    Thread.Sleep(1000);                    Console.WriteLine("AsycyCallBackCurrentMoneyPersonA:{0}", f.EndInvoke(r));                    Console.WriteLine("AsycyCallBackRunTimePersonA:{0}", (DateTime.Now - now).TotalSeconds);                    Console.WriteLine("AsycyCallBackSaveBankAccountPersonA thread IsBackground " + Thread.CurrentThread.IsBackground);                }, null);                while (!ar.IsCompleted)                {                    Console.WriteLine("threadT1 wating current run at treadID:" + Thread.CurrentThread.ManagedThreadId);                    Thread.Sleep(50);                }            });            Thread t2 = new Thread(() =>            {                Console.WriteLine("Running in a thread t2.");                Func<decimal, int, decimal> f = (money, ms) =>                {                    Console.WriteLine("SaveBankAccountPersonB thread started! current run at threadID:" + Thread.CurrentThread.ManagedThreadId);                    Console.WriteLine("SaveBankAccountPersonB thread IsBackground " + Thread.CurrentThread.IsBackground);                    Thread.Sleep(ms);                    Console.WriteLine("SaveBankAccountPersonB thread completed!");                    return ++money;                };                var ar = f.BeginInvoke(1, 200, (r) =>                {                    if (r == null)                    {                        throw new ArgumentNullException("r");                    }                    Console.WriteLine("AsycyCallBackCurrentMoneyPersonB:{0}", f.EndInvoke(r));                    Console.WriteLine("AsycyCallBackRunTimePersonB:{0}", (DateTime.Now - now).TotalSeconds);                    Console.WriteLine("AsycyCallBackSaveBankAccountPersonB thread IsBackground " + Thread.CurrentThread.IsBackground);                }, null);                while (!ar.IsCompleted)                {                    Console.WriteLine("threadT2 wating current run at treadID:" + Thread.CurrentThread.ManagedThreadId);                    Thread.Sleep(50);                }            });            t1.Start();            t2.Start();            t1.Abort();            Console.WriteLine("This ia a mian thread.");            Console.ReadKey();        }    }}

There are a lot of code above, which is used to expand the previous article. Enable two threads t1 and t2 respectively, and add asynchronous Delegate A and B to each thread to start A new background thread (asynchronous delegate is A background thread by default)

As shown in the figure above, t1 has not been run yet, and it has stopped. in the figure below, t1 is running.

However, A is still not running, which fully indicates that A is stopped by t1.

 

Background threads A and B have two callback functions at the same time. The Sleep (1000) latency is added to the callback function for 1 second, followed by the external t1.Abort (); the foreground thread t1 is ended. As A result, background thread A has not come and ended when the front-end thread t1 ends (in fact, it is mandatory and ends with the front-end thread t1 !)

This verifies the fact that the foreground thread ends and ends with the lazy background thread! Code is the best description

 

Summary: The foreground Thread and background Thread described in this section are demonstrated on the basis of the Thread class, the life cycle of the background thread ends with the end of the lazy foreground thread.

At the same time, we will further illustrate asynchronous and multithreading. The thread is just an asynchronous implementation method!

 

To be continued...

 

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.