First, lay out some basic knowledge

stay .net 4.5 In the Async Await keyword , With the previous version of Task To make it easier to develop asynchronous programs .
 
Before using them Let's take care of it first Why use them . like One person does a few things , Then he has to do it one by one , And if you add a couple of people to do it together
Obviously the task will be done faster . That's what parallel means .
 
In the program , The common performance bottleneck is NetWork I/O bottleneck , CPU bottleneck , database I/O bottleneck , These bottlenecks make our program run very slowly , We try to optimize . Because parallel development itself aggravates CPU burden , So parallel is generally used to optimize By the other two I/O The bottleneck caused by .
//sync method sample
public static void DownLoadWebPage()
{
//TODO cost 5s
Console.WriteLine( "DownLoadWebPage on Thread:{0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep();
Console.WriteLine( "End downloading the page.." );
} public static void LoadDatafromDB()
{
//TODO cost 5s
Console.WriteLine( "LoadDataFromDB on Thread:{0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep();
Console.WriteLine( "End loading Data.." );
}
For example, the two methods here , adopt Thread.Sleep To simulate the time-consuming process 5 second , So if we write another method to call
 public static void OurSyncJob()
{
Console.WriteLine( "start doing things sync" );
DownLoadWebPage();
LoadDatafromDB();
//do some other things
Console.WriteLine( "do some other things" );
}
Obviously It will take more than 10s The clock , If we use task Start two threads At the same time as follows
 public static async Task OurAsyncJobTask()
{
Console.WriteLine( "start doing things async" );
var taskA= Task.Run(() => { DownLoadWebPage(); });
var taskB= Task.Run(() => { LoadDatafromDB(); });
await Task.WhenAll(taskA,taskB);
Console.WriteLine( "do some other things" );
}
The execution time will only be 5s A little more , Greatly improved the performance of our program .
 
After understanding the basics , Let's talk about the actual application scenarios of asynchronous programs .
We call WebApi When , Because it has to be transmitted through the network , Sometimes it's very slow . Now it's time for us to show our skills with asynchronism .
our webapi as follows
 public class ProductController : ApiController
{
public productRepo repo = new productRepo();
public IEnumerable< Product> getProducts()
{
Thread.Sleep();
return repo.GetAll();
}
}
public class WidgetController : ApiController
{
public widgetRepo repo = new widgetRepo();
public IEnumerable< Widget> getWidgets()
{
Thread.Sleep();
return repo.GetAll();
}
}
It's all simulation time consuming 5 Second , Now we're going to call these at the same time api get Data and show it together
 public static List <Product > TaskGetProduct()
{
using( HttpClient client= new HttpClient())
{
client.BaseAddress = new Uri( "http://localhost:52593/" );
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue ("application/json" ));
string json = client.GetString("api/Product/Products" );
return JsonConvert.DeserializeObject< List< Product>>(json);
}
}
Obviously Call this webapi want 5 A second more , So when we want to get it at the same time , We have to call... Separately TaskGetProduct() TaskGetWidget() TaskGetGizmos()
Like the previous experience , If it's synchronized, it's impossible 15 A second more .. How to bear it ..
It's obvious to get it asynchronously
public static async Task< List< Product>> TaskGetProduct()
{
using( HttpClient client= new HttpClient())
{
client.BaseAddress = new Uri( "http://localhost:52593/" );
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue ("application/json" ));
string json = await client.GetStringAsync("api/Product/Products" );
return JsonConvert.DeserializeObject< List< Product>>(json);
}
} public static async Task< pwgVM> RunTaskGetAll()
{
var task1 = TaskGetItem< Product>();
var task2 = TaskGetItem< Gizmos>();
var task3 = TaskGetItem< Widget>();
await Task.WhenAll(task1,task2,task3);
pwgVM vm = new pwgVM(task1.Result,task2.Result,task3.Result);
return vm;
}
Three tasks at the same time , cost 5 A second more .ok
 
  Attach source code  
http://files.cnblogs.com/files/JasonShenW/WebApi.rar
http://files.cnblogs.com/files/JasonShenW/WebMVC.rar
 

Async Await Asynchronous call WebApi More articles about

  1. .NET Web Why should we use async/await Asynchronous programming

    Preface What is? async/await? await and async yes .NET Framework4.5 frame .C#5.0 Technology in grammar , The goal is to simplify the asynchronous programming model . async and await The relationship between ? asy ...

  2. 【 turn 】C# Async/Await Best practices in asynchronous programming

    Async/Await Best practices in asynchronous programming Stephen Cleary recently , There's a lot about Microsoft .NET Framework 4.5 Added right to async and await the ...

  3. take async/await Convert asynchronous code to secure, deadlock free, synchronous code

    stay async/await Asynchronous model ( namely TAP Task-based Asynchronous Pattern) Before appearance , There's a lot of synchronization code in the code base , So much so that all the code has migrated to async/awa ...

  4. C# in Thread,Task,Async/Await Asynchronous programming

    What is asynchronous Synchronous and asynchronous are mainly used to modify methods . When a method is called , The caller needs to wait for the method to finish executing and return to continue , We call this method synchronous : When a method is called, it immediately returns , And get a thread to execute the internal business of the method , transfer ...

  5. spring boot Use in @Async Implement asynchronous call task

    This article mainly introduces spring boot Use in @Async Implement asynchronous call task , Xiaobian thinks it's very good , Now share with you , Also give you a reference . Let's follow Xiaobian to have a look What is? “ Asynchronous call ”? “ Asynchronous call ” The corresponding is “ Sync ...

  6. async/await Asynchronous processing demo

    async/await Asynchronous processing demo Download address : async/await Asynchronous processing demo

  7. spring boot Study ( 11、 ... and ) Use @Async Implement asynchronous call

    Use @Async Implement asynchronous call What is? ” Asynchronous call ” And ” A synchronous invocation ” “ A synchronous invocation ” That is, the program is executed in a certain order ,, Each line of program code must wait for the last line to be executed :” Asynchronous call ” So long as the last line of code is executed , There is no need to wait ...

  8. Spring Boot Use @Async Implement asynchronous call

    original text :http://blog.csdn.net/a286352250/article/details/53157822 project GitHub Address : https://github.com/FrameRes ...

  9. Deep understanding of Xiecheng ( Four ):async/await Asynchronous crawler combat

    Contents of this article : Crawling blog titles synchronously async/await Asynchronously crawling blog titles This film is a supplement to the series of articles on in-depth understanding of synergetic process . You will learn from this article :async/await How to use the actual crawler . Case study from CSDN On ...

Random recommendation

  1. Java in List According to the value of the object's property, the database is created group by Operation of functions

    public class test { public static void main(String[] args) { List<Bill> list = new test().setO ...

  2. 【 turn 】Mac Installation in system homebrew( similar redhat|Centos Medium yum; similar Ubuntu Medium apt-get)

    Homebrew,Homebrew abbreviation brew, yes Mac OSX Package management tools on , Can be in Mac Easy to install or uninstall software in , so to speak Homebrew Namely mac Under the apt-get.yum Artifact Homebr ...

  3. 【HDOJ】1930 And Now, a Remainder from Our Sponsor

    Simple string . #include <stdio.h> #define MAXLEN 160 char buf[MAXLEN]; ], parts[]; void getpart(int x) ...

  4. python_Opencv_ Handle mouse events

    technological process : First , Create a mouse event callback function , When a mouse event occurs, it is executed . Mouse events can be any action on the mouse , For example, press the left button , Release left key , Double left click, etc . We can get the coordinates of the image corresponding to the mouse through the mouse event . According to these ...

  5. c The fourth language assignment

    ( One ) Correct the wrong questions Output triangle area and perimeter , Enter the three sides of the triangle a.b.c, If you can make a triangle , Output area area And perimeter perimeter( Retain 2 Decimal place ): otherwise , Output "These sides do ...

  6. In integers x Number of occurrences

    Find out 1~13 In the integer of 1 Number of occurrences , And work out 100~1300 In the integer of 1 Number of occurrences ? For this reason, he counted 1~13 Contained in the 1 The number of is 1.10.11.12.13 So there is 6 Time , But he has no way to deal with the latter problems .ACMer ...

  7. 【redis】windows How to close redis

    install redis Then enter... In the command line window redis-server redis.windows.conf start-up redis To close a command line window is to close redis.---redis As windows Service startup mode r ...

  8. 14 Super fashion HTML5 Clock animation

    Clock animation is also widely used in web applications , In some personal blogs , We often see something quite personal HTML5 Clock animation . Today we share with you 14 Super fashion in different shapes HTML5 Clock animation , One of them is the disk clock .3D The clock . Personalized clock, etc ...

  9. a After clicking on the tag , to a Tag add style

    window.onload=function(){ var a = document.getElementById("cate").getElementsByTagName(&qu ...

  10. Codeforces Round #394 (Div. 2) D. Dasha and Very Difficult Problem

    D. Dasha and Very Difficult Problem time limit per test:2 seconds memory limit per test:256 megabyte ...