Asynchronous Programming with Async and Await
C#
This snippet is taken from MSDN, I think it’s the best sample to illustrate how to use async
and await
in C#. Sorry for the lack of syntax highlight, I can’t embed Gist because here we have no access within the GFW.
1 | // Three things to note in the signature: |
If you want to change your synchronous functions to asynchronous ones, pay attention to the return value type. Use Task
for the function that has void
as return value type, use Task<T>
for the function that use T
as return value type.
1 | void -> Task |
By the way, you can still use Task<void>
for certain purpose, we will talk about this later.
Naming Convention
By convention, it is suggested to append “Async” to the names of methods that have an Async or async modifier.
JavaScript (ES2016, aka ES7)
1 | async function mySleep(timeout) { |
JavaScript is famous for asynchronous execution, in this example we create a sleep function which is supposed to hold current thread for timeout
milliseconds. In the anonymous function, we use two parameters resolve
and reject
to revoke back to main thread.
The execution result is probably like this:
1 | Do some thing, Mon Feb 26 2016 21:52:11 GMT+0800 (CST) |
If you want to run this example, don’t forget to enable ES7 for Node.js.
TypeScript
In the third pick I’d like to show you how to use async/await in TypeScript. It always gives me the feeling that TypeScript and C# share many cool features, at least in the syntax level. Well probably this is what is call Microsoft Style.
1 | async function delay(ms: number) { |
Ok, like ES7 above, we defined a synchronous function delay which will resolve after ms
milliseconds. Then we create a action ping()
which will print ping xxxx
after the delay of 1 second.
How to run this? Create a TypeScript project with tsc --init
, which will generate a tsconfig.json
file, change the target to ES6
. Here’s my configuration:
1 | { |
Run tsc
in the folder you will get a JavaScript file with the same filename as your script file. Run it with node
, et Voilà.
Furthermore
Here’s the generated file from above ts
script, you can ignore this part if you are not interested in how this was implemented by TypeScript.
1 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { |
* * *
After Everything
How can you generate a title that contains only C#
in markdown? Use this:
1 | # C# |