winforms 在C#中异步等待仍会阻塞UI

n3schb8v  于 2022-11-17  发布在  C#
关注(0)|答案(1)|浏览(184)

我使用以下代码执行SourceCreator方法,而不阻塞UI。

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。有人能告诉我为什么吗?

vkc1a9a2

vkc1a9a21#

这里实际上并没有使用任何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;
}

如果你想使用StreamReader,你可以这样做

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))
    using (var stream = response.Content.ReadAsStreamAsync())
    using (var reader = new StreamReader(stream))
    {
        var a = // do stuff with reader here
        return a;
    }
}

相关问题