A detailed description of Thread,task,async/await,iasyncresult code in C #

Source: Internet
Author: User
This article mainly introduces the knowledge of Thread,task,async/await,iasyncresult in C #. Have a certain reference value, follow the small series below to see it

Speaking of Async, thread,task,async/await,iasyncresult these things must not be around, and today we will talk about them in turn

1. Threads (thread)

The meaning of multithreading is that in an application, there are multiple execution parts that can be executed at the same time, for more time-consuming operations such as io,http://www.php.cn/php/php-database-operations.html "target=" _blank "> Database operations), or wait for a response (such as WCF communication) operation, you can open a background thread to execute, so that the main thread will not block, can continue to execute, wait until the background thread executes, then notify the main thread, and then make the corresponding action!

Opening new threads in C # is easier

static void Main (string[] args) {Console.WriteLine ("Main thread Start");//isbackground=true, set it as a background thread t = new Thread (Run) {is Background = true};   T.start (); Console.WriteLine ("The main thread is doing something else!") "); After the main thread ends, the background thread will automatically end, regardless of whether or not execution completed//thread.sleep (300); Thread.Sleep (1500); Console.WriteLine ("Main thread End");} static void Run () {thread.sleep (700); Console.WriteLine ("This is a background thread call");}

Execution results such as,

You can see that after starting the background thread, the main thread continues to execute, and not wait until the background thread finishes executing.

1.1 Thread Pool

Imagine, if there are a lot of tasks to deal with, such as the site behind the HTTP request processing, it is not to create a background thread for each request? Obviously inappropriate, this consumes a lot of memory, and the process of creating frequently can seriously affect the speed. The thread pool is designed to solve this problem by saving the created threads into a thread pool (with multiple threads in it), and when the task is to be processed, if there are idle threads in the thread pool (the thread will not be recycled and will be set to idle when the previous task is completed), then the thread in the thread pool is directly invoked ( example, the Application object in the ASP. NET processing mechanism),

Use case:

for (int i = 0; i < i++) {ThreadPool.QueueUserWorkItem (M = = {  Console.WriteLine) (Thread.CurrentThread.Manage Dthreadid.tostring ()); });} Console.read ();

Operation Result:

You can see that, although it was executed 10 times, it did not create 10 threads.

1.2 Signal Volume (Semaphore)

Semaphore is responsible for coordinating threads and can limit the number of threads accessed for a resource

Here is a simple example of the use of the Semaphoreslim class:

static Semaphoreslim Semlim = new Semaphoreslim (3); 3 indicates that at most three threads can access the static void Main (string[] args) {for (int i = 0; i <; i++) {  new Thread (semaphoretest). Start (); } console.read ();} static void Semaphoretest () {semlim.wait (); Console.WriteLine ("Thread" + Thread.CurrentThread.ManagedThreadId.ToString () + "Start Execution"); Thread.Sleep (2000); Console.WriteLine ("Thread" + Thread.CurrentThread.ManagedThreadId.ToString () + "execution complete"); Semlim.release ();}

The results of the implementation are as follows:

As you can see, only three threads are executing at the beginning, and a new thread will execute the method after a thread has finished executing and releasing it!

In addition to the Semaphoreslim class, you can also use the semaphore class, feel more flexible, interesting words can search, here do not do a demonstration!

2.Task

The task is. NET4.0 joins, similar to the function of the thread pool ThreadPool, when a new task is opened with a task, the thread is called from the thread pool, and thread creates a new thread each time it instantiates.

Console.WriteLine ("Main thread Boot");//task.run start a thread//task start a background thread, to wait for the background thread to finish executing in the main thread, you can call the Wait method//task Task = Task.Factory.StartNew (() = {thread.sleep (1500); Console.WriteLine ("Task Start"); }); Task task = Task.run (() = {  thread.sleep (1500); Console.WriteLine ("Task Start");}); Thread.Sleep (); task. Wait (); Console.WriteLine ("Main thread End");

The results of the implementation are as follows:

How to open a new task: Task.run () or Task.Factory.StartNew (), open a background thread

To wait for the background thread to finish executing in the main thread, you can use the Wait method (which executes synchronously). No wait is executed asynchronously.

Compare task and Thread:

static void Main (string[] args) {for (int i = 0; i < 5; i++) {  new Thread (RUN1). Start (); } for (int i = 0; i < 5; i++) {  Task.run (() = {Run2 ();});}} static void Run1 () {Console.WriteLine ("Thread Id =" + Thread.CurrentThread.ManagedThreadId);} static void Run2 () {Console.WriteLine ("Thread Id of the task call =" + Thread.CurrentThread.ManagedThreadId);}

Execution Result:

As can be seen, directly with thread will open 5 threads, with a task (using the thread pool) opened 3!

2.1 task<tresult>

Task<tresult> is the return value type, which is the Task,tresult with the return value.

Console.WriteLine ("Main thread Start");//The return value type is stringtask<string> task = Task<string>. Run (() = {Thread.Sleep (+);  return Thread.CurrentThread.ManagedThreadId.ToString (); });//will wait until the task execution is finished before it is output; Console.WriteLine (Task. Result); Console.WriteLine ("Main thread End");

Operation Result:

Through task. Result can be taken to the return value, if the value of the time, the background thread has not finished, it will wait for the completion of its execution!

Simply mention:

Task tasks can be canceled by the CancellationTokenSource class, the feeling is not used much, the usage is relatively simple, interesting words can be searched!

3. async/await

Async/await is introduced in c#5.0, first use:

static void Main (string[] args) {Console.WriteLine ("-------Main thread start-------"); task<int> task = Getstrlengthasync (); Console.WriteLine ("Main thread continues execution"); Console.WriteLine ("Task returned value" + task.) Result); Console.WriteLine ("-------Main thread End-------");} Static async task<int> Getstrlengthasync () {Console.WriteLine ("Getstrlengthasync method starts Execution");//The <string returned here > String type, not task<string> string str = await GetString (); Console.WriteLine ("Getstrlengthasync Method Execution End"); Return str. Length;} Static task<string> GetString () {//console.writeline ("GetString method begins execution") return task<string>. Run (() = {  Thread.Sleep (+);  return value of "GetString"; });}

Async is used to modify the method to indicate that the method is asynchronous, and that the declared method must have a return type of: Void,task or task<tresult>.

An await must be used to decorate a task or task<tresult>, and only in an async method that is now decorated with the Async keyword. In general, async/await appear to be meaningful,

Look at the results of the operation:

As you can see, after the main function calls the Getstrlengthasync method, it is executed synchronously until the await keyword is encountered, and the main function returns to continue execution.

Does the program automatically open a background thread to execute the GetString method when it encounters the await keyword?

Now add that line of comments in the GetString method, and the result is:

As you can see, after encountering the await keyword, we did not proceed with the operation after the Getstrlengthasync method, and did not immediately return to the main function, but instead executed the first line of GetString. In this case, the await does not open a new thread to execute the GetString method, but instead synchronizes the GetString method to execute the Task<string> in the GetString method. Run (), the background thread was opened by task!

So what is the role of await?

Can literally understand that the above mentioned task.wait can let the main thread wait for the background thread to finish, await and wait similar, wait, wait for task<string> Run () begins the background thread execution, except that the await does not block the main thread and only causes the Getstrlengthasync method to pause execution.

So how is the await done? Have you opened a new thread to wait?

Only two threads (main thread and task open threads)! As to how to do it (I do not know ......>_<), everyone is interested in the study under it!

4.IAsyncResult

IAsyncResult since. NET1.1, a class that contains a method that is asynchronous can implement it, and the task class implements that interface

How to achieve asynchrony without the help of a task?

Class program{static void Main (string[] args) {Console.WriteLine ("Main program starts--------------------");  int threadId;  Asyncdemo ad = new Asyncdemo (); Asyncmethodcaller caller = new Asyncmethodcaller (AD.  TestMethod); IAsyncResult result = caller.  BeginInvoke (3000,out threadId, NULL, NULL);  Thread.Sleep (0); Console.WriteLine ("Thread thread {0} is running.", Thread.CurrentThread.ManagedThreadId)//will block the thread until the background thread finishes executing the result.  Asyncwaithandle.waitone (); Console.WriteLine ("The main program is doing something!!!"  "); Gets the result of the asynchronous execution of string returnvalue = caller.  EndInvoke (out threadId, result); Frees resource result.  Asyncwaithandle.close ();  Console.WriteLine ("Main program End--------------------"); Console.read (); }}public class asyncdemo{//method for background thread execution public string TestMethod (int callduration, out int threadId) {Console.WriteLine ("  The test method begins execution. ");  Thread.Sleep (callduration);  ThreadId = Thread.CurrentThread.ManagedThreadId; Return String.Format ("Time for test method execution {0}.", callduration.tostring ()); }}public delegate string Asyncmethodcaller (int callduration, out int threadId); 

The key step is the part of the red font that runs the result:

The difference between the usage and the task is not very great! Result. Asyncwaithandle.waitone () is similar to a task's wait.

5.Parallel

Finally, a simple way to turn on multithreading in a loop:

Stopwatch watch1 = new Stopwatch (); Watch1. Start (); for (int i = 1; i <=; i++) {Console.Write (i + ","); Thread.Sleep (1000);} Watch1. Stop (); Console.WriteLine (Watch1. Elapsed); Stopwatch watch2 = new Stopwatch (); Watch2. Start ();//Call thread in the thread pool Parallel.For (1, one, I =>{Console.WriteLine (i + ", thread ID:" + Thread.CurrentThread.ManagedThreadId ); Thread.Sleep (1000);}); Watch2. Stop (); Console.WriteLine (WATCH2. Elapsed);

Operation Result:

Cyclic list<t>:

list<int> list = new List<int> () {1, 2, 3, 4, 5, 6, 6, 7, 8, 9}; parallel.foreach<int> (list, n =>{Console.WriteLine (n); Thread.Sleep (1000);});

Execute action[] Array inside the method:

action[] actions = new action[] {  new action (() =>{  Console.WriteLine ("Method 1");}), New Action (() =>{  Console.WriteLine ("Method 2"); })}; Parallel.Invoke (actions);
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.