简体   繁体   中英

Async await still blocking the UI in C#

I used following code to execute the SourceCreator method without blocking 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;
}

Here is button click event

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;
}

I run this code, but this still blocking my UI of Windows form app. Could somebody tell me why?

You are not actually using any async methods here. You are just passing it to a Task constructor, which is not how you are supposed to do it, and may not work with the WinForms' SynchronizationContext .

HttpWebRequest is effectively deprecated, you should switch to HttpClient instead. And that has a full complement of async methods.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM