A simple description of the 1.async
Prior to version 4.5, to implement asynchronous methods, the use of multithreading goes hand in hand. and 4.5 directly an async-modified method with await implementation asynchronous, here the principle of the underlying implementation is not studied,
Should be essentially the same as the operation on the thread.
2.A simple example of async
Note: Async-Modified method, the return value is qualified:void,task,task<t> general situation we are not going to wait for an asynchronous processing result
public class Asynccalc
{
static Asynccalc _asynccalc = null;
public static Asynccalc Default {
get {
if (_asynccalc = = null) _asynccalc = new Asynccalc ();
return _asynccalc;
}
}
Public async void Add (int a, int b)
{
var C = await AddEx (A, b);
Console.WriteLine ("ADD:" + C);
}
<summary>
Addition asynchronous implementation Body
</summary>
<param name= "a" ></param>
<param name= "B" ></param>
<returns></returns>
Public task<int> addex (int a, int b)
{
Return Task.run (() =
{
int C = a + B;
Thread.Sleep (2000);
return C;
});
}
Public async void MUL (int a, int b)
{
var c= await Mulex (A, b);
Console.WriteLine ("MUL:" + C);
}
Public task<int> Mulex (int a, int b) {
Return Task.run (() = {
var C = A * b;
Thread.Sleep (1000);
return C;
});
}
}
Use the console call to output the result (sleep here is the time it takes to simulate data processing, no actual effect)
static void Main (string[] args)
{
int a = ten, B = 10;
Console.WriteLine ("Program starts! ");
AsyncCalc.Default.Add (A, b);
AsyncCalc.Default.MUL (A, b);
Console.WriteLine ("The program is finished! ");
Thread.Sleep (3100);
}
Thread.Sleep (3100); it is to wait for the output to be asynchronous, and if you don't wait, you won't see the result.
The result of the above output:
This result + process at a glance
These methods are relatively scattered, can be summarized
<summary>
Asynchronous execution methods (simple encapsulation, depending on the project)
</summary>
<param name= "func" ></param>
<param name= "Callback" ></param>
Public async void RunAsync (Action func)
{
Func<task> Taskqueue = () = () = {
Return Task.run (() = {
Func ();
});
};
await Taskqueue ();
}
New features of the. NET Framework 4.5 Async (asynchronous) Preliminary understanding