C# 线程死锁案例
代码如下
public partial class Form1 : Form { private readonly HttpClient httpClient = new HttpClient(); public Form1() { InitializeComponent(); } private async Task DownloadWebsitesAsync() { Liststring>> downloadWebsiteTasks = new List string>>(); foreach (var site in Contents.WebSites) { downloadWebsiteTasks.Add(DownloadWebSiteAsync(site)); } //这一步会造成deadlock,应为 var results = Task.WhenAll(downloadWebsiteTasks).Result;//Result指示阻塞当前线程(UI),等待结果返回 foreach (var result in results) { //界面打印结果 Textbox.Text += result; } } private async Task<string> DownloadWebSiteAsync(string url) { //ConfigureAwait指示线程返回后,回到当前线程(UI) var response = await httpClient.GetAsync(url).ConfigureAwait(false);//改成false,继续使用线程池里的线程运用下面的代码,避免死锁 var responsePayloadBytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);//改成false,继续使用线程池里的线程运用下面的代码,避免死锁 //回到UI线程返回字符串 return $"Finish downloding data from {url}. Total bytes returned {responsePayloadBytes.Length}. {Environment.NewLine}"; } private async void AsyncDownload_Click(object sender, EventArgs e) { Textbox.Text = ""; var stopwatch = Stopwatch.StartNew(); await DownloadWebsitesAsync(); Textbox.Text += $"Elapsed time: {stopwatch.Elapsed}{Environment.NewLine}"; } private void Result_TextChanged(object sender, EventArgs e) { } }