herry jack
herry jack

Reputation: 11

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?

Upvotes: 1

Views: 816

Answers (1)

Charlieface
Charlieface

Reputation: 72480

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

If you want to use a StreamReader you can do it like this

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

Upvotes: 3

Related Questions