异步测试代码
System.Diagnostics.Debug.Print("start"); new Thread(new ThreadStart(new Action(() => { for (int i = 0; i < 10; i++) { System.Diagnostics.Debug.Print(i + " "); } System.Diagnostics.Debug.Print("Thread over"); }))).Start(); System.Diagnostics.Debug.Print("Main over");
输出
"start" "Main over" "0 " "1 " "2 " "3 " "4 " "5 " "6 " "7 " "8 " "9 " "Thread over"
效果是主线程已经结束了,子线程才开始
var url = "http://h5.ktgj.com/"; var list_task = new List<Task<string>>(); for (int i = 0; i < 10; i++) { var temp_url = url + i; var task = Task.Run(async () => { System.Diagnostics.Debug.Print("temp_url=" + temp_url); var client = new System.Net.Http.HttpClient(); var html = await client.GetStringAsync(temp_url); System.Diagnostics.Debug.Print("temp_url=" + temp_url + " is ok"); return html; }); list_task.Add(task); } Task.WaitAll(list_task.ToArray()); foreach (var item in list_task) { System.Diagnostics.Debug.Print(item.Result); }
Task.WaitAll()
等所有请求都返回了html,才开始后续处理
//await Task.WhenAll(task1, task2, task3); //ThreadPool.QueueUserWorkItem(_ => //{ // Thread.Sleep(1000); // Thread.Sleep(10); System.Diagnostics.Debug.Print("ThreadPool.QueueUserWorkItem"); //}); ////不使用await:Task多线程 //Task.Run(() => //{ // Thread.Sleep(1000); // Thread.Sleep(10); System.Diagnostics.Debug.Print("Task.Run"); //});