如何使用WebClients DownloadStringAsync来避免冻结UI?

时间:2015-07-25 23:50:17

标签: c# multithreading asynchronous webclient webclient-download

我试图找出如何让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 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;
    }

1 个答案:

答案 0 :(得分:2)

考虑使用更简单的WebClient.DownloadStringTaskAsync方法,以便您使用async-await个关键字。

代码看起来像这样:

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