Task异步
2019-04-13 11:19 huoit 阅读(168) 评论(0) 收藏 举报快速示例
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
1、如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!
2、欢迎各位转载,但是未经作者本人同意,转载文章请在文章页面明显位置标明作者和原文连接,否则保留追究法律责任的权利。
作者博客: http://www.cnblogs.com/xmai/