user5156226
user5156226

Reputation: 17

How do i use WebClients SYNCHRONOUS DownloadString function without blocking the UI?

im trying to download a string on a separate non ui thread and when it is done downloading update the ui, but i want to do it without the ui freezing, so i tried to make a thread but that didnt work, and then i tried to make a thread in that thread but that also didnt work how do i call the downloadstring function without freezing the ui?

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 web = new Thread(() => webDownload(url));
        web.Start();

    }
    // Go (sorting) button
    private void button2_Click(object sender, EventArgs e)
    {

    }
    public void webDownload(string address)
    {
        Thread next = new Thread(() => downloading(address));
        next.Start();
        //  next.Join();

    }
    public void downloading(string address){

        using (WebClient client = new WebClient())
        {
           string content = client.DownloadString(address);
           textBox2.BeginInvoke(new displayDownloadDelegate(displayDownload), content);

        }

   }
    private void displayDownload(string content)
    {
        textBox2.Text = content;
    }

Upvotes: 0

Views: 2478

Answers (1)

sstan
sstan

Reputation: 36523

Though you could simply use async-await with the asynchronous WebClient.DownloadStringTaskAsync method, if you really must use the synchronous WebClient.DownloadString method (for some reason) by executing it on a separate non-ui thread, you can still do that pretty simply with Task.Run() and async-await:

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

    using (WebClient client = new WebClient())
    {
        textBox2.Text = await Task.Run(() => client.DownloadString(url));
    }
}

Upvotes: 2

Related Questions