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. C# 清楚Cookies

    //销毁Cookies中的数据 if (Request.Cookies["Ticket"] != null) { HttpCookie mycookie; mycookie = R ...

  2. Codeforces Round #331 (Div. 2) C. Wilbur and Points

    C. Wilbur and Points time limit per test 2 seconds memory limit per test 256 megabytes input standar ...

  3. iOS 10 版本适配问题收集-b

    随着iOS10发布的临近,大家的App都需要适配iOS10,下面是我总结的一些关于iOS10适配方面的问题,如果有错误,欢迎指出. 1.系统判断方法失效: 在你的项目中,当需要判断系统版本的话,不要使 ...

  4. android 弹出框(输入框和选择框)

    1.输入框: final EditText inputServer = new EditText(this); inputServer.setFilters(new InputFilter[]{new ...

  5. shell dev null 是什么

    1:在不想把标准输出和标准出错信息输出到控制台,也不想重定向到文件时经常使用 2:不能忽略其读入功能.从/dev/null读入时都是0 3:系统的垃圾桶,类似于Windows的回收站,不同的是这个设备 ...

  6. curPos和tgtPos

    curpos tgtpos 乍一看以为是当前位置和目标位置,但在项目里面这两个位置有点坑 当客户端玩家移动或者AI里面的位置,会把获得的位置付给tgtpos 而以前的tgtpos会付给curpos 所 ...

  7. 并行编译加快 VS C++ 项目的编译速度

    最近编译的项目都比较大,话说自己的电脑配置还行,但编译所花的时间还是很长,遇到需要重新编译整个项目的时候真的有回宿舍睡一觉的冲动.昨天一不小心被我发现了一款软件Xoreax IncrediBuild ...

  8. Eclipse插件开发

    最近在做Eclipse的插件开发,目前是在Eclipse3.x环境上进行开发,之后迁移到Eclipse4.x环境.会贡献在插件开发过程中遇到的所有问题以及相关技巧,敬请期待. SWT开发 JFace开 ...

  9. 浅析白盒审计中的字符编码及SQL注入

    尽管现在呼吁所有的程序都使用unicode编码,所有的网站都使用utf-8编码,来一个统一的国际规范.但仍然有很多,包括国内及国外(特别是非英语国家)的一些cms,仍然使用着自己国家的一套编码,比如g ...

  10. 【Android自学之旅】 Android开发环境的搭建

    [Android自学之旅] Android开发环境的搭建 搭建参考教程: http://www.oracle.com/technetwork/java/javase/downloads/jdk7-do ...