- 概念
- 线程:线程是操作系统能够进行运算调度的最小单位,被包含在进程之中,是进程中的实际运作单位。
-
同步:一定要等任务执行完了,得到结果,才执行下一个任务。如果程序执行耗时操作时会阻塞线程。
- 应用场景
- UI与I/O: UI发出I/O操作,I/O操作是费时任务
-
计算密集型工作(CPU-bound):多线程
-
IO密集型工作(I/O-bound):异步多线程机制
- 实例代码
public partial class MainForm : Form { /// <summary> /// Http连接对象 /// </summary> private readonly HttpClient httpClient = new HttpClient(); private readonly List<string> DownloadUrlList = new List<string> { "https://www.jd.com", "https://www.tmall.com", "http://book.dangdang.com", "https://www.cnblogs.com", "https://www.runoob.com", "https://www.csdn.net", "https://www.githubs.cn", "https://cn.vuejs.org", "https://msdn.itellyou.cn", "https://www.iconfont.cn", "https://www.baidu.com", "https://cn.bing.com", "https://docs.microsoft.com/zh-cn/windows", "https://docs.microsoft.com/zh-cn", "https://docs.microsoft.com/zh-cn/dotnet/csharp", "https://www.12306.cn", "https://hotels.ctrip.com", "http://www.shooting.org.cn", "https://www.issf-sports.org", "https://www.cba.net.cn", "https://uland.taobao.com", "https://top.baidu.com" }; public MainForm() { InitializeComponent(); } private void ReportResult(string result) { txtReport.Text += result; } /// <summary> /// 同步下载按钮点击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSync_Click(object sender, EventArgs e) { txtReport.Text = ""; Stopwatch stopwatch = Stopwatch.StartNew(); Download(); txtReport.Text += $"Elapsed time:{stopwatch.Elapsed}.{Environment.NewLine}"; } /// <summary> /// 同步下载:下载时UI线程会卡顿、直到下载结束后才恢复 /// </summary> private void Download() { foreach (var url in DownloadUrlList) { HttpResponseMessage response = httpClient.GetAsync(url).Result; string responsePayloadBytes = response.Content.ReadAsStringAsync().Result; ReportResult($"Finish downloading data for {url}.Total bytes {responsePayloadBytes.Length}.{Environment.NewLine}"); } } /// <summary> /// 异步下载按钮点击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btnAsync_Click(object sender, EventArgs e) { txtReport.Text = ""; Stopwatch stopwatch = Stopwatch.StartNew(); await DownloadAsync(); txtReport.Text += $"Elapsed time:{stopwatch.Elapsed}.{Environment.NewLine}"; } /// <summary> /// 异步下载: /// 1、程序运行时不影响UI线程 /// 2、虽然不影响UI线程,但是下载速度并没有变化 /// </summary> /// <returns></returns> private async Task DownloadAsync() { foreach (var url in DownloadUrlList) { ReportResult(await DownloadWebSitePayloadAsync(url)); } } private async Task<string> DownloadWebSitePayloadAsync(string url) { HttpResponseMessage response = await httpClient.GetAsync(url); string responsePayloadBytes = await response.Content.ReadAsStringAsync(); return $"Finish downloading data for {url}.Total bytes {responsePayloadBytes.Length}.{Environment.NewLine}"; } /// <summary> /// 异步多线程按钮点击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btnAsyncMultithreading_Click(object sender, EventArgs e) { txtReport.Text = ""; Stopwatch stopwatch = Stopwatch.StartNew(); await MultithreadingDownloadAsync(); txtReport.Text += $"Elapsed time:{stopwatch.Elapsed}.{Environment.NewLine}"; } /// <summary> /// 异步多线程:UI不会卡顿且大幅提升程序性能 /// </summary> /// <returns></returns> private async Task MultithreadingDownloadAsync() { List<Task<string>> downloadTasks = new List<Task<string>>(); DownloadUrlList.ForEach(o => downloadTasks.Add(DownloadWebSitePayloadAsync(o))); var results = await Task.WhenAll(downloadTasks); foreach (var result in results) { ReportResult(result); } }
}
总结:多线程虽然可以在一定程度上提升程序性能,但是使用时需要谨慎选择,如果使用不当的话会出现超预期的效果。
标签:www,浅谈,c#,private,https,多线程,com,cn From: https://www.cnblogs.com/xulian1990/p/17517408.html