c#|【NET多线程】C#多线程异步请求多个url地址


异步测试代码

System.Diagnostics.Debug.Print("start"); new Thread(new ThreadStart(new Action(() => { for (int i = 0; i < 10; i++) { System.Diagnostics.Debug.Print(i + "\r\n"); }System.Diagnostics.Debug.Print("Thread over"); }))).Start(); System.Diagnostics.Debug.Print("Main over");


输出
"start" "Main over" "0\r\n" "1\r\n" "2\r\n" "3\r\n" "4\r\n" "5\r\n" "6\r\n" "7\r\n" "8\r\n" "9\r\n" "Thread over"


效果是主线程已经结束了,子线程才开始

var url = "http://h5.ktgj.com/"; var list_task = new List>(); 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); }

【c#|【NET多线程】C#多线程异步请求多个url地址】
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"); //});


转载于:https://www.cnblogs.com/jhli/p/9213615.html

    推荐阅读