C# Tutorials - Herong's Tutorial Examples - v3.32, by Herong Yang
"async" Function Example
A tutorial example is provided on how to write an 'async' function with Task<T> return type. An 'async' function needs an 'await' expression to trigger a child thread to split executions.
After having a good understanding on how "await" expressions work, we can take a closer look at "async" functions.
According to the C# 5 specification, an "async" function works under the following rules:
The invocation of an "async" function goes roughly like this:
Since we have existing tutorial examples on "await" expressions from previous tutorials, we can modify one of them to create an "async" function with Task<int> as the return type, AsyncFunctionTest.cs:
// AsyncFunctionTest.cs // Copyright (c) 2016 HerongYang.com. All Rights Reserved. using System; using System.Net.Http; using System.Threading.Tasks; public class AsyncFunctionTest { static void Main() { Task<int> t = AwaitTest(); Console.WriteLine("Let me wait for it..."); int l = t.Result; Console.WriteLine("Length of response body: "+l); } async static Task<int> AwaitTest() { string uri = "https://www.herongyang.com/Service/Hello_REST.php"; HttpClient c = new HttpClient(); Console.WriteLine("Calling GetStringAsync()..."); Task<string> t = c.GetStringAsync(uri); Console.WriteLine("Evaluating await-expression ..."); string s = await t; Console.WriteLine("Writing GET response body ..."); Console.WriteLine(s); return s.Length; } }
If you compile and run this tutorial example with .NET Framework 4.6.1 SDK, you will get:
C:\herong>%NET%\csc "/r:%REF%/System.Net.Http.dll" AsyncFunctionTest.cs C:\herong>AsyncFunctionTest Calling GetStringAsync()... Evaluating await-expression ... Let me wait for it... Writing GET response body ... <Result> <Message> Hello from server - herongyang.com. </Message> </Result> Length of response body: 87
Wonderful! Everything went exactly as expected.
This tutorial example, AsyncFunctionTest.cs, actually creates an "async" function as a wrapper of the GetStringAsync() method from the System.Net.Http.HttpClient class.
Table of Contents
Logical Expressions and Conditional Statements
Visual C# 2010 Express Edition
C# Compiler and Intermediate Language
Compiling C# Source Code Files
MSBuild - Microsoft Build Engine
GetStringAsync() Method in HttpClient Class
GetStringAsync() Method Example Program
Watching Asynchronous Operation Execution Status
"await" Expression and Child Thread
"await" Expression Thread Example
System.Diagnostics.FileVersionInfo Class
WPF - Windows Presentation Foundation