异步多线程解决界面卡顿问题
异步多线程解决界面卡顿问题
点击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); }); } } }