user3743168
user3743168

Reputation: 67

How do I use WebClients DownloadStringAsync to avoid freezing the UI?

Im trying to figure out how to get the ui to stop freezing whenever i do a buttonclick, i want the button click to download a string, ive tried the async functions, and the synchronous functions, and adding one thread, then adding two threads, but i cant figure out how to make it work. This is my most recent attempt could someone explain to me what im missing? Im using a thread here because i read that the async function call doesnt necessarily spin up a new thread.

public partial class Form1 : Form
{
    private delegate void displayDownloadDelegate(string content);
    public Thread downloader, web;
    public Form1()
    {
        InitializeComponent();
    }
    // Go (Download string from URL) button
    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Enabled = false;

        string url = textBox1.Text;
        Thread t = new Thread(() =>
        {
            using (var client = new WebClient())
            {
                client.DownloadStringCompleted += (senderi, ei) =>
                {
                    string page = ei.Result;
                    textBox2.Invoke(new displayDownloadDelegate(displayDownload), page);
                };

                client.DownloadStringAsync(new Uri(url));
            }
        });
        t.Start();
    }
    private void displayDownload(string content)
    {
        textBox2.Text = content;
    }

Upvotes: 1

Views: 2406

Answers (1)

sstan
sstan

Reputation: 36523

Consider using the more straight-forward WebClient.DownloadStringTaskAsync method that allows you to use the async-await keywords.

The code would simply look like this:

private async void button1_Click(object sender, EventArgs e)
{
    textBox1.Enabled = false;

    string url = textBox1.Text;
    using (var client = new WebClient())
    {
        textBox2.Text = await client.DownloadStringTaskAsync(new Uri(url));
    }
}

Upvotes: 3

Related Questions