异步多线程解决界面卡顿问题
异步多线程解决界面卡顿问题
点击button下载一个网页,并将网页的长度显示在textbox中。
注意是将网页的长度显示在textbox中,而不是将下载的网页字符显示在textbox中,因为太大的字符串在textbox上显示本身就会卡界面。
using System; using System.Net; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp6 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //private void button1_Click(object sender, EventArgs e) //{ // textBox1.Text = "";//每次点击按钮清空 // //第一个例子,卡界面 // WebClient webClient = new WebClient(); // string html = webClient.DownloadString("https://www.163.com"); // this.textBox1.Text = html.Length.ToString(); //} //private void button1_Click(object sender, EventArgs e) //{ // textBox1.Text = "";//每次点击按钮清空 // //第二个例子,通过多线程解决不卡界面 // WebClient webClient = new WebClient(); // Task.Run(() => // { // string html = webClient.DownloadString("https://www.163.com"); // this.Invoke(new Action(() => // { // this.textBox1.Text = html.Length.ToString(); // })); // }); //} //private async void button1_Click(object sender, EventArgs e) //{ // textBox1.Text = "";//每次点击按钮清空 // //第三个例子,使用HttpClient的异步多线程,不卡界面 // HttpClient Client = new HttpClient(); // string html = await Client.GetStringAsync("https://www.163.com"); // this.textBox1.Text = html.Length.ToString(); //} //private async void button1_Click(object sender, EventArgs e) //{ // textBox1.Text = "";//每次点击按钮清空 // //第四个例子,将WebClient改造成异步,实现不卡界面 // WebClient webClient = new WebClient(); // string html = await Task.Run(() => // { // return webClient.DownloadString("https://www.163.com"); // }); // this.textBox1.Text = html.Length.ToString(); //} //private async void button1_Click(object sender, EventArgs e) //{ // textBox1.Text = "";//每次点击按钮清空 // //第四个例子的变形,写一个WebClient的异步方法,实现不卡界面 // string html = await getDownloadAsync("https://www.163.com"); // this.textBox1.Text = html.Length.ToString(); //} //private Task<string> getDownloadAsync(string url) //{ // WebClient webClient = new WebClient(); // return Task.Run(() => // { // return webClient.DownloadString(url); // }); //} private async void button1_Click(object sender, EventArgs e) { textBox1.Text = "";//每次点击按钮清空 //第四个例子的变形,写一个WebClient的异步方法,实现不卡界面 Task<string> t = getDownloadAsync("https://www.163.com"); string html = await t; this.textBox1.Text = html.Length.ToString(); } private Task<string> getDownloadAsync(string url) { WebClient webClient = new WebClient(); return Task.Run(() => { return webClient.DownloadString(url); }); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?