Windows 8 series (7): use Asynchronous APIs: await and async

Source: Internet
Author: User

One of the biggest differences between Windows 8 Metro programming and Windows Phone and Silverlight is that a large number of asynchronous APIs are used, and these Apis usually have no corresponding synchronous APIs, therefore, we need to know how to use Asynchronous APIs in Metro-style applications.

 

When using asynchronous APIs, we may inevitably encounter two keywords: await and async. The following describes the advantages and specific usage of asynchronous APIs.

Asynchronous APIs generally take a long time to return results or complete (for example, I. O. operation ). Assume that after clicking a button,ProgramReads a large local file.

1. if you read the data in synchronous mode, the program cannot perform other operations at the same time during the period before the result is returned. For example, if you click again, that is to say, your program is blocked.

2. If it is changed to asynchronous operations, the program will execute this line.CodeThe application will temporarily exit the time processing program. It can process other users while waiting for the returned results, until the following code is successfully returned.

 (LongitudeDamon. TianNote: The code is modified here, And the return type should be task <bool>)

PrivateAsync task <Bool>Issuccess (StringFilename,StoragefolderFolder ){VaRFile =Await folder. createfileasync (filename, creationcollisionoption. openifexists );StringTempstring ="Wow!";
Return true ;}

This is the file reading API. The await keyword used here indicates that the asynchronous interface is called.And wait until the result is returned before executing the code (remember this sentence and we will talk about it later).

Let's take a look at this function using the keyword async during definition. This is because at least one part of this function uses the await keyword, so this function must be defined as async. You can use the await keyword when calling this function. For example:

Bool result = await issuccess (filename, folder );

Similarly, the function of the above line of code must also declare the async keyword.

 

Next, the question is, do these two keywords have to be written? Can it be unnecessary? The answer is yes.

If the await keyword is not used when an asynchronous API is called, it is also possible.

We also take the above function as an example.This is also possible, but a warning is generated during compilation: The await keyword is not used.

VaRFile =Folder. createfileasync (filename, creationcollisionoption. openifexists );

 

What are the differences between the two statements? The answer is: the code execution sequence has changed.And the type of the returned results has changed..

If await is not used when an asynchronous API is called, the program will not wait for the API to return the result before executing the following code, but will directly execute the following code:

That is to say, if the code looks like the following, then when the file has not been successfully assigned a value (when the createfileasync function has not returned the result), The tempstring has been assigned a value.

 (If await is not included, the returned file is no longer of the storagefile type but iasyncoperation <storagefile> type)

 
PrivateAsync task <Bool>Issuccess (StringFilename,StoragefolderFolder ){VaRFile =Folder. createfileasync (filename, creationcollisionoption. openifexists );StringTempstring ="Wow!";
Return true ;}

 

 

For example, a warning is usually displayed in the pop-up box of the application. For example, if we write a demo and publish a blog post successfully, the system warning box is displayed. Below are public functions: the system warning box is displayed.

 

 

 
PublicAsyncStatic VoidAlert (StringMessage,StringTitle ="") {Messagedialog DLG=NewMessagedialog (message, title); await DLG. showasync ();}

 

 

Code 1:

 
Alert ("You have not logged on."); Alert ("Please log on!");

 

 

Code 2:

 
Await alert ("You have not logged on."); Await alert ("Please log on!");

 

 

The execution results of the above two sections of code are different. The first section of code will pop up two pop-up boxes consecutively. The first pop-up box is "You have not logged on yet .", Then, "Log on!" appears !", The second pop-up box is displayed on the first pop-up box.

In code 2, the first warning is displayed. If you do not log on, click "OK" to close the dialog box. The second dialog box is displayed.

 

Note the following:

Await cannot be usedSimilarLock Block Code:

 

Lock(Tempstring ){//Await cannot be used here}

 

 Lamda expressions can be written in this way.

 
This. Loaded + = async (sender, argS) =>
{
Await...
};

 

The above is my personal profile. If you have any questions or different suggestions, please join us and discuss them to better pave the way for Win8 development!

 

 

My weibo: Why is http://weibo.com/345169632?

My blog: http://www.cnblogs.com/lihaiyin

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.