快速示例
class Program { static void Main(string[] args) { //Console.WriteLine("main start.."); //AsyncMethod(); //// //Console.WriteLine("main end.."); String ss = "aa"; Console.WriteLine(ss.GetType()); Console.WriteLine(ss.GetType()==typeof(string)); Console.ReadLine(); } static async void AsyncMethod() { try { Console.WriteLine("start async"); HttpContent _content = new StringContent("", Encoding.UTF8); _content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var _client = new HttpClient(); var _response = _client.PostAsync("http://github.com", _content).Result; var _json_result = _response.Content.ReadAsStringAsync().Result; Thread.Sleep(1000); Console.WriteLine("end async"); throw new Exception("huhuhu"); } catch (Exception e) { Console.WriteLine(e); } //return 1; } static async Task<int> MyMethod() { for (int i = 0; i < 5; i++) { Console.WriteLine("Async start:" + i.ToString() + ".."); await Task.Delay(1000); //模拟耗时操作 } return 0; } }
返回
class Program { static void Main(string[] args) { Task<List<Product>> tk1 = Task<List<Product>>.Factory.StartNew(() => SetProduct()); Task.WaitAll(tk1); Console.WriteLine(tk1.Result.Count); Console.WriteLine(tk1.Result[0].Name); Console.ReadLine(); } static List<Product> SetProduct() { List<Product> result = new List<Product>(); for (int i = 0; i < 500; i++) { Product model = new Product(); model.Name = "Name" + i; model.SellPrice = i; model.Category = "Category" + i; result.Add(model); } Console.WriteLine("SetProduct 执行完成"); return result; } }
http://www.cnblogs.com/woxpp/p/3928788.html