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

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

我想弄清楚如何让 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;
    }

考虑使用更直接的 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));
    }
}