[英]Async await still blocking the UI in C#
我使用以下代碼在不阻塞 UI 的情況下執行SourceCreator
方法。
string a =null;
private string SourceCreator()
{
string sum = textBox7.Text;
sum = sum.Replace(" ", "+");
string url = string.Format("https://www.aliexpress.com/wholesale?catId=0&initiative_id=SB_20220824221043&SearchText={0}&spm=a2g0o.productlist.1000002.0", sum);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
// richTextBox2.Text += sr.ReadToEnd();
a = sr.ReadToEnd();
sr.Close();
return a;
}
這是按鈕單擊事件
private async void Timer4_Tick(object sender, EventArgs e)
{
Task<string> task1 = new Task<string>(SourceCreator);
task1.Start();
string p = await task1;
textBox10.Text = p;
}
我運行此代碼,但這仍然阻止了我的 Windows 表單應用程序的 UI。 有人能告訴我為什么嗎?
您實際上並沒有在這里使用任何async
方法。 您只是將它傳遞給Task
構造函數,這不是您應該這樣做的方式,並且可能不適用於 WinForms 的SynchronizationContext
。
HttpWebRequest
已被有效棄用,您應該改用HttpClient
。 這有完整的異步方法。
static HttpClient _client = new HttpClient();
private async Task<string> SourceCreator(string sum)
{
sum = sum.Replace(" ", "+");
string url = $"https://www.aliexpress.com/wholesale?catId=0&initiative_id=SB_20220824221043&SearchText={sum}&spm=a2g0o.productlist.1000002.0";
using (var response = await _client.GetAsync(url))
{
var a = await response.Content.ReadAsStringAsync();
return a;
}
}
private async void Timer4_Tick(object sender, EventArgs e)
{
string p = await SourceCreator(textBox7.Text);
textBox10.Text = p;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.