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. 删除word文档中表格后的空行

    处理办法为: 方法1:使上.下页边距数值缩小,从而使页面扩大能容纳下这一段落行.   方法2:光标处于最后段落行符号前,右键→段落→缩进和间距→间距→行距→固定值→设置值→1磅→确定.

  2. 爬虫组NABC

    Need(需求): 我们小组的研究课题是编写一个更实用的爬虫软件,编写时会应用到学长的部分代码并在其基础上完善创新. 鉴于学长代码已经实现了基本功能,即从网站上面爬取相关的Word文档等与计算机有关的 ...

  3. c语言编程之循环队列

    利用链表实现的循环队列,完成了队列的入队和出队,对于队空和队满用了一个flag进行标记.入队flag++,出队flag-- #include"stdio.h" typedef in ...

  4. HTML & XML 转义字符

    HTML & XML 转义字符 HTML中<, >,&等有特殊含义,(前两个字符用于链接签,&用于转义),不能直接使用.使用这三个字符时,应使用它们的转义序列,如下 ...

  5. Careercup - Google面试题 - 5732809947742208

    2014-05-03 22:10 题目链接 原题: Given a dictionary, and a list of letters ( or consider as a string), find ...

  6. 团队项目-smart原则

    Smart原则 Specific ——明确性 所谓明确就是要用具体的语言清楚地说明要达成的行为标准.明确的目标几乎是所有成功团队的一致特点.很多团队不成功的重要原因之一就因为目标定的模棱两可,或没有将 ...

  7. sqlserver 类似oracle的rownum功能: row_number

    select row_number() over(order by t.id ) as num,id,name from (SELECT distinct [列 0] as id ,[列 1] as ...

  8. ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

    引子: 本项目在老电脑上用的是oracle10g,换新电脑装的是oracle11g,但运行项目本没有什么关系,本来说创建个用户,用PLSQL手工导入数据,再改几下配置文件即可跑起来--但实际启动中遇到 ...

  9. 解决Tomcat 7遇到StackOverflowError的异常

    参考网址:http://qingyuexiao.iteye.com/blog/1886059 前言:在写此博客前,首先感谢姚双琪.林瑞丰.网友qingyuexiao的倾囊相助!此博文不过是笔者对于他们 ...

  10. 在线最优化求解(Online Optimization)之一:预备篇

    在线最优化求解(Online Optimization)之一:预备篇 动机与目的 在实际工作中,无论是工程师.项目经理.产品同学都会经常讨论一类话题:“从线上对比的效果来看,某某特征或因素对xx产品的 ...