Async Programming Series No. 04 Write Async method

Source: Internet
Author: User

Write in front

Learning Async, a friend recommended the "async in c#5.0", did not find the Chinese version, coincidentally also want to improve the English, with my poor English translation of some important parts, purely entertainment, simple sharing, keep learning, remember humility.

If you think this is a bad thing to translate, just step on it. If you feel worthy of encouragement, thank you for leaving your praise, may love the technology of the park friends in the future every time should be a drastic breakthrough, do not choose to quit. In each time should think independently, do not choose to drift, should go all out, do not choose to do their best, live up to every second the meaning of existence.

Reprint and crawler Please indicate the original link http://www.cnblogs.com/tdws/p/5645075.html, blog park snail June 27, 2016.

Directory

The No. 01 chapter introduces the asynchronous programming

The No. 02 Chapter Why asynchronous Programming is used

No. 03 Manual Asynchronous code Writing

No. 04. Writing Async Methods

The No. 05 Chapter What is the await?

No. 06. Task-based Asynchronous Pattern

No. 07. Some tools for asynchronous code

No. 08 Chapter which thread is running your code

No. 09. Exceptions in Asynchronous programming

The 10th chapter uses asynchronous programming in parallel

11th Unit Test Your async code

The 12th Chapter ASP. NET applications for asynchronous programming

13th. Asynchronous Programming in WINRT applications

14th. What does the compiler do for your async at the bottom?

15th performance of asynchronous code

Writing Async Methods

Now that we know how great the async code is, but is it hard to write? It's time to take a look at c#5.0 's async function. As we saw in chapter three earlier, an async method allows to include the await keyword.

Private asyncvoid dumpwebpageasync (stringnew  WebClient (); string page = awaitwebclient.downloadstringtaskasync (URI); Console.WriteLine (page);}

Because the await keyword is in this method, the await here does not continue down until the download ends the recovery process. This processing makes this method asynchronous, and in this chapter we will explore such asynchronous methods.

Convert the sample code to async (last example in Chapter two)

We now convert the previous example to async. If you can, open the original code and try to convert it to async and await before you read it down.

The most important method is Addfavicon, that is, the method of adding the downloaded icons to the UI interface. We want to program it asynchronously so that the UI thread is free to go to the appropriate user during the download. The first step is to add the Async keyword to the method. It is at the same signature location as the static keyword.

Then we need to wait for the download using await. Await the role of the hospital operator in C # syntax, just like '! ' or ' (type) conversion operator '. He is placed on the left side of an expression, meaning an asynchronous wait expression.

Finally, the call to the Downloaddata method must be replaced by a call to asynchronous version DownloadDataAsync.

Async methods are not automatically asynchronous. The Async method simply makes it easier to invoke (consume consume) other asynchronous methods. They run synchronously, until they call the Async method and await it. When they do such things, they must make themselves asynchronous. Sometimes, an async method does not await anything.

Private asyncvoid Addafavicon (stringnew  WebClient (); byte [] bytes = Awaitwebclient.downloaddatataskasync ("http// " "/ Favicon.ico"); Image ImageControl = makeimagecontrol (bytes); M_WrapPanel.Children.Add (ImageControl);}

Compare this approach with the version described in the previous section. This looks more like the synchronous code. There is no additional method, only a little extra code under the same structure. However, his behavior is similar to the version we wrote in one of the sections in the previous chapter (click to jump).

Task and await

Let's break down the await we wrote. Here is the Webclient.downloadstringtaskasync method.

task<string> Downloadstringtaskasync (string address)

Its return type is task<string>. As I described in the section on task, the task represents an action in execution. And its subclass task<t> represents an operation that returns the result of a T type at some point in the future. You can assume that task<t> promises to return a value of type T after this time-consuming operation.

Both task and task<t> can represent asynchronous operations, and both have the ability to make callbacks after the operation is complete. In a manually implemented asynchronous approach, you use the ContinueWith method to pass a delegate that allows the code to proceed to the next step after the time-consuming operation is completed. Await executes your remaining code in the same way (that is, the code after the await).

If you apply await to task<t>, he becomes an await expression, and the entire expression has a type T. This means that you can wait for the result of a variable, and you can use it in the rest of the second half of the method, as we saw in the example. However, when you await a non-generic task, it remains in an await state, but cannot be assigned to anything, just like calling a void method. This means that, as a task does not promise to return any value, he simply represents the operation itself.

await Smtpclient.sendmailasync (MailMessage);

Nothing can separate our await expressions, so we can access the task directly, or do something else in the wait. Just look at the code and the comments and you'll see.

task<string> MyTask = webclient.downloadstringtaskasync (URI); // Do something here string await MyTask;

It is important to fully understand the revelation it brings. The Downloadstringtaskasync method executes on the first line, he starts executing asynchronously on the current thread, and once the download is started, it returns a task<string> (as compared to the above code), which is still in the current thread. Only later when we await task<string>, the compiler does something special. If you write an await in and call an async method in one line of code it is always correct. Translator Interpretation: This means that if the await method is called, the thread is the current thread when performing an await internal operation. After performing an await operation, it is possible that the current thread will handle the following code, or it may be a new thread to handle the subsequent code. In other words, the method awaited by await is executed by the current thread, but the execution is immediately returned to the thread pool, and the next operation randomly selects a thread to execute. So I think it's wrong to say that the await will open a new thread. Again, the new thread occurs after an await, because the thread that executes the await is reclaimed into the pool, and then fetched from the thread pool to execute the following code. Await does not have the ability to turn on the thread at all.

Once the call to Downloadstringtaskasync occurs, the time-consuming operation starts executing, which gives us a very simple way to perform multiple asynchronous operations. We can start multiple operations, keep tasks, and then await them.

task<string> Firsttask = Webclient1.downloadstringtaskasync ("http://oreilly.com " ); Task<string> Secondtask = Webclient2.downloadstringtaskasync ("http/ simple-talk.com"); string await Firsttask; string await secondtask;

Waiting for multiple tasks is a dangerous way, and maybe they will throw an exception. If two operations throw an exception, the first await will propagate its exception, which means that the secondtask will never be waiting. Its exception may not be noticed and depends. NET version and settings, may be lost or thrown in another unintended thread, and may also terminate the process. We're going to deal with it in the seventh chapter in a better way.

Async method Return type

There are three return types for methods marked Async:

void

· Task

· Task<t>

There is no other allowed return type, because the method does not end when it returns normally. Typically, an async method will await a time-consuming operation, meaning that the method will return quickly, but in the future results can be achieved. It also means that there is no definite result when the method returns, but later it becomes available.

I'll show you the difference between the method return value-for example, task<string>-the return type, which the programmer intends to return to the caller, in this case a string type. Typically, in a non-asynchronous method, the return type and the result type are the same. But the difference between them is important for the Async method.

It is clear that the void return type is a reasonable choice in asynchronous programming scenarios. An async void method is an asynchronous operation that "triggers and forgets". The caller cannot wait for any returned results, and cannot know when the operation ended or whether it succeeded. You should use void when you are sure that you do not need to know when the operation ends or is successful. The most common scenario for async void is in the case of async code and other code boundaries, such as UI event processing that must return void.

The Async method that returns a task allows the caller to wait for the result of the operation to end and pass an exception during asynchronous code execution. When we don't need any return class value, an async task method is better than the Async void method because he allows the caller to wait with await and to handle the exception more easily. (The most suitable case of void is mentioned earlier).

Finally, the task<t> async method, like Task<string>, is returned, usually for asynchronous operations that require a return value.

Async, method signatures, and interfaces

The Async keyword appears on the declaration of the method, just like public and static. However, async cannot be used for the signature of a method, whether it is overriding the method, implementing an interface, or when it is being tuned.

The only effect of the Async keyword is to compile within the method he applies, rather than other keywords, to determine how it interacts with the outside world. Because of this, the rules on overriding methods, defining interfaces, are completely disregarded.

class baseclass{     publicvirtualasync task<int> alexsmethod ()    {     ...    }} class subclass:baseclass{    // This overrides Alexsmethod abovepublic              override task<int> alexsmethod ()    {        ...    }}

The interface cannot be defined using async, which is simple because it is not necessary. If an excuse requires a method to return a task, you can use async when you implement it, but don't use it as a way of doing your own thing. The interface does not need to specifically declare whether or not to be asynchronous.

Return Statement of the Async method

The Return statement behaves differently in asynchronous methods. Think of the normal non-async method, using Return statement depends on the return type of the method.

void method

Return statement only need to return, and is selectable. (no writing is OK)

Returns a method of type T

Return must have an expression of type T, such as 5+x, and must be at the end of all paths of the method.

In a method marked async, different conditions also have different rules

void method and method for returning task

Return statement only need to return, and is selectable. (no writing is OK)

Ways to return to task>t<

Return must return an expression of T and be at the end of all return paths.

In Async methods, the return type and expression type of a method are different. The compiler transformation can be thought of as wrapping your result value before returning it to the caller. Of course, task>t< is actually created immediately, and once your time-consuming operation is finished, your value is "populated". Translator: As mentioned in the previous chapters, the Async method immediately returns the value of "wrapped" and populates the value after execution finishes.

Asynchronous methods are contagious

As we can see, the best way to use the task returned by async is to await it in an async method. When you do this, your method usually returns a task as well. In order to enjoy the advantages of async style, the code you invoke the method must not wait for your task to end in a blocking way, and then your caller is likely to await you.

The following example is a method I've written that reads how many characters are in a Web page and returns them asynchronously.

Private Async task<int> Getpagesizeasync (string  url) {    new  WebClient ();     string await webclient.downloadstringtaskasync (URL);     return page. Length;}

To using it, I need to the write another async method, which returns its result asynchronously in order to use it, I need to write another asynchronous way to return the results of my own, just like this:

Private Asynctask<string> Findlargestwebpage (string[] URLs) {     stringlargest =NULL; intLargestsize =0; foreach(stringUrlinchURLs) {          intSize =awaitgetpagesizeasync (URL); if(Size >largestsize) {Size=largestsize; Largest=URL; }      }       returnlargest;}

Under this mage, we do not have to write Async method chains, just every time we await. Async is an infectious programming model that can easily diffuse into the entire code system. But I think this is precisely because the Async method is so easy to write, which is perfectly fine.

Asynchronous anonymous delegates and Lambdas

A common naming method can be asynchronous, and there are two anonymous methods that can be asynchronous. Grammar and normal methods are also very similar. The following is an example of how to use asynchronous anonymous delegates:

func<task<intasyncdelegatereturn3; };

Here is the async lambda:

func<task<stringasync"hello";

There's nothing different about normal async code rules. You can use them to keep your code clear and tidy, snap-closed, and non-asynchronous methods to write in exactly the same form.

Written in the last

Recently good confused, may be a little too impatient, always feel underachievement, desperately want to go higher, and see their obvious progress. Pain.

The next section will describe what the await has done.

Async Programming Series No. 04 Write Async method

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.