C # 5.0 is about to usher in the Async and await keywords, and in fact you can now experience the use of, download Microsoft Visual Studio Async CTP after installation, you can experience the fun of these two keywords in VS2010. (Microsoft Visual Studio Async CTP may have conflicts with some vs patches, please see http://www.cnblogs.com/jeekun/archive/2011/09/28/2193950.html for detailed download of installation
Now we turn our attention back to the use of these two keywords, you must know that these two keywords are used for asynchronous operation, in fact, these two keywords there is no mystery to say,
Async must be added to the function declaration, if you do not add the Async keyword, the function can not use the await keyword, just so
Await can only be used to wait for a task or task<t> to perform an asynchronous return, just so
For the use and details of the task class, see. NET 4.0 Parallel programming, where the task is simply considered a thread.
Now the online example, the same is the operation of WebClient download pictures and so on, this example really can not let us meet, how to use these two keywords in their own code. Here's the simplest example.
Class program
{
private static async void Test ()
{
task<int> t = new task<int> (() => {thre Ad. Sleep (3000); return 1; });
T.start ();
int tr = await t;
Console.WriteLine (tr);
}
static void Main (string[] args)
{
Test ();
Console.WriteLine ("Main");
Console.readkey ();
}
The test function uses the two keywords in the simplest way, executes the code, outputs "Main" first, and then prints "1" after 3 seconds.
Some something:
1, when using await, should be careful, in fact, this keyword can be seen as another manifestation of yield, that is, this keyword will lead to the end of the function, such as you in the main function if the use of this keyword, then congratulations, The code after await does not run until the program ends, because the function has been temporarily returned.
2,await corresponding task must start first, in fact, you can think of a task as a multithreaded, multithreading is not start,await of course will not get results, await code will not have the opportunity to call.