标签:
先铺垫一些基础知识
//sync method sample public static void DownLoadWebPage() { //TODO cost 5s Console.WriteLine( "DownLoadWebPage on Thread:{0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); Console.WriteLine( "End downloading the page.." ); } public static void LoadDatafromDB() { //TODO cost 5s Console.WriteLine( "LoadDataFromDB on Thread:{0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); Console.WriteLine( "End loading Data.." ); }
public static void OurSyncJob() { Console.WriteLine( "start doing things sync" ); DownLoadWebPage(); LoadDatafromDB(); //do some other things Console.WriteLine( "do some other things" ); }
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" ); }
public class ProductController : ApiController { public productRepo repo = new productRepo(); public IEnumerable< Product> getProducts() { Thread.Sleep(5000); return repo.GetAll(); } } public class WidgetController : ApiController { public widgetRepo repo = new widgetRepo(); public IEnumerable< Widget> getWidgets() { Thread.Sleep(5000); return repo.GetAll(); } }
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); } }
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; }
标签:
原文地址:http://www.cnblogs.com/JasonShenW/p/5193785.html