Skip to main content
 首页 » 编程设计

c#之如何使用 WebClient DownloadStringAsync 来避免卡住 UI

2024年06月03日45cloudgamer

我试图弄清楚如何让用户界面在我单击按钮时停止卡住,我希望按钮单击以下载字符串,我尝试了异步函数和同步函数,并添加一个线程,然后添加两个线程,但我不知道如何让它工作。这是我最近的尝试,有人可以向我解释我缺少什么吗?我在这里使用一个线程,因为我读到异步函数调用不一定会启动一个新线程。

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