Control Flow in Async Programs

You can write and maintain asynchronous programs more easily by using the Async and Await keywords.

However, the results might surprise you if you don't understand how your program operates.

This topic traces追溯 the flow of control through a simple async program to show you when control moves from one method to another and what information is transferred each time.

In general, you mark methods that contain asynchronous code with the Async (Visual Basic) or async (C#) modifier.

In a method that's marked with an async modifier, you can use an Await (Visual Basic) or await (C#) operator to specify where the method pauses to wait for a called asynchronous process to complete.

For more information, see Asynchronous Programming with Async and Await (C# and Visual Basic).

The following example uses async methods to download the contents of a specified website as a string and to display the length of the string.

The example contains the following two methods.

  • startButton_Click, which calls AccessTheWebAsync and displays the result.

  • AccessTheWebAsync, which downloads the contents of a website as a string and returns the length of the string.

AccessTheWebAsync uses an asynchronous HttpClient method, GetStringAsync(String), to download the contents.

Numbered display lines appear at strategic战略上的 points throughout the program to help you understand how the program runs and to explain what happens at each point that is marked.

The display lines are labeled "ONE" through "SIX."

The labels represent the order in which the program reaches these lines of code.

The following code shows an outline of the program.

需要添加对System.Net.Http.dll的引用,

 private async void button1_Click(object sender, EventArgs e)
{
//One
Task<int> getLengthTask = AccessTheWebAsync(); //Four
int concentLength = await getLengthTask; //Six
textBox1.Text = $"Length of downloaded string is {concentLength}";
} private async Task<int> AccessTheWebAsync()
{
//Two
HttpClient httpClient = new HttpClient();
Task<string> getStringTask = httpClient.GetStringAsync("http://www.cnblogs.com/chucklu/"); //Three
string urlContents = await getStringTask;
Console.WriteLine(urlContents); //Five
return urlContents.Length;
}

Each of the labeled locations, "ONE" through "SIX," displays information about the current state of the program.

The following output is produced.

ONE:   Entering startButton_Click.
Calling AccessTheWebAsync. TWO: Entering AccessTheWebAsync.
Calling HttpClient.GetStringAsync. THREE: Back in AccessTheWebAsync.
Task getStringTask is started.
About to await getStringTask & return a Task<int> to startButton_Click. FOUR: Back in startButton_Click.
Task getLengthTask is started.
About to await getLengthTask -- no caller to return to. FIVE: Back in AccessTheWebAsync.
Task getStringTask is complete.
Processing the return statement.
Exiting from AccessTheWebAsync. SIX: Back in startButton_Click.
Task getLengthTask is finished.
Result from AccessTheWebAsync is stored in contentLength.
About to display contentLength and exit. Length of the downloaded string: 33946.

Control Flow in Async Programs的更多相关文章

  1. Core Java Volume I — 3.8. Control Flow

    3.8. Control FlowJava, like any programming language, supports both conditional statements and loops ...

  2. 《CS:APP》 chapter 8 Exceptional Control Flow 注意事项

    Exceptional Control Flow The program counter assumes a sequence of values                            ...

  3. Asynchronous JS: Callbacks, Listeners, Control Flow Libs and Promises

    非常好的文章,讲javascript 的异步编程的. ------------------------------------------------------------------------- ...

  4. 异步 JS: Callbacks, Listeners, Control Flow Libs 和 Promises【转载+翻译+整理】

    http://sporto.github.io/blog/2012/12/09/callbacks-listeners-promises/ 或 http://www.ruanyifeng.com/bl ...

  5. CSAPP Chapter 8:Exception Control Flow

    prcesssor在运行时,假设program counter的值为a0, a1, ... , an-1,每个ak表示相对应的instruction的地址.从ak到ak+1的变化被称为control ...

  6. SSIS的 Data Flow 和 Control Flow

    Control Flow 和 Data Flow,是SSIS Design中主要用到的两个Tab,理解这两个Tab的作用,对设计更高效的package十分重要. 一,Control Flow 在Con ...

  7. Control Flow 如何处理 Error

    在Package的执行过程中,如果在Data Flow中出现Error,那么Data Flow component能够将错误行输出,只需要在组件的ErrorOutput中进行简单地配置,参考<D ...

  8. 关于Control flow

    1.一个package包含一个control flow并且一个或多个data flow. (这个项目叫做 Integration services project,提供了三种不同类型的control  ...

  9. SSIS ->> Control Flow And Data Flow

    In the Control Flow, the task is the smallest unit of work, and a task requires completion (success, ...

随机推荐

  1. 【img】 图片是怎么存储的

    用ue 打开一张图片,动动手脚,出现卡碟的画面效果. 可不可以用C#来做一个图片编辑器? 怎么做?路线怎么走? 稍后揭晓答案 根据实际操作获取类一些基础知识: 1. 文件是二进制存储的,为了便于查看编 ...

  2. verilog逻辑复制

    本文转自:http://www.cnblogs.com/linjie-swust/archive/2012/03/27/FPGA_verilog.html 在FPGA设计中经常使用到逻辑复制,逻辑复制 ...

  3. 关于WP8 微信分享的补充说明

    1.根据微信官方Demo完成相应功能. 2.在分享完后,从微信回来,需要进行 快速恢复. 3.在快速恢复中加入 RootFrame.Navigating += HandlerFotResetNavig ...

  4. RCP,TCP,C/S,B/S

    RCP: RICH CLIENT PROGRAM   胖客户端 TCP: THIN CLIENT PROGRAM   瘦客户端 CS: CLIENT SERVER             客户端/服务 ...

  5. margin-top相对谁的问题

    根据规范,一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会和其内部文档流中的第一个子元素的上边距重叠.意思便是:如果你只想margin相对于父标 ...

  6. Linux内核分析作业一

    一.实验 通过反汇编一个简单的c语言程序来分析计算机是如何工作的 1.进入实验楼,在实验楼环境下把c语言代码转换成汇编码 汇编代码如下图: 二.汇编代码的工作过程中堆栈的变化:(手绘步骤,顺序是从左到 ...

  7. 复习linq

    复习linq linq的英文是language integrated query.其中query的意思就是疑问或者计算机用语就是从资料库中提取信息的要求,可以理解为查询的意思.那么它翻译过来的话就是集 ...

  8. unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor

    eclipse启动项目时,提示超时: 解决方案: 修改 workspace\.metadata\.plugins\org.eclipse.wst.server.core\servers.xml文件.  ...

  9. centos nginx,php添加到Service

    SHELL脚本: nginx vim /etc/init.d/nginx #!/bin/sh # # nginx - this script starts and stops the nginx da ...

  10. XCode签名证书死活不能选

    Editors>Show Values on Xcode , then you can select the code sign instead of typing