Task.Delay()
Task.Delay(3000);// 不会阻塞UI线程
Thread.Sleep(3000) ;// 会阻塞UI线程
private async void button1_Click(object sender, EventArgs e)
{
await Task.Delay(3000);// 不会阻塞UI线程
textBox1.Text = "1111";
}
HttpClient
在程序用调用Http接口、请求http资源、编写http爬虫等的时候都需要在程序集中进行Http请求。
很多人习惯的 WebClient
、HttpWebRequest
在TPL下有很多用起来不方便的地方,TPL下推荐使用HttpClient
(using System.Net.Http;
),.netcore下已经不支持WebClient
、HttpWebRequest
等。
如何编写异步方法
private Task<string> TestAsync()
{
return Task.Run(() =>
{
Thread.Sleep(3000);
return "hello";
});
}
private async void button1_Click_1(object sender, EventArgs e)
{
string s = await TestAsync();
// 等待上条代码执行完才往下继续执行
textBox1.Text = s;
}
private void button2_Click(object sender, EventArgs e)
{
TestAsync();
// 不会等待上条代码执行完就往下继续执行
textBox1.Text = "111";
}
如何封装异步方法
// 不带返回值
private async Task DownloadHtml1Async(string url)
{
using (HttpClient httpClient = new HttpClient())
{
string html = await httpClient.GetStringAsync(url);
}
}
// 带返回值
private async Task<int> DownloadHtml2Async(string url)
{
using (HttpClient httpClient = new HttpClient())
{
string html = await httpClient.GetStringAsync(url);
return html.Length;
}
}
private async void button3_Click(object sender, EventArgs e)
{
await DownloadHtml1Async("https://laravel.com/");
// 等待上条代码执行完才往下继续执行
textBox1.Text = "222";
}
private void button4_Click(object sender, EventArgs e)
{
DownloadHtml1Async("https://laravel.com/");
// 不会等待上条代码执行完就往下继续执行
textBox1.Text = "333";
}