gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:32 31 4
gpt4 key购买 nike

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

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

关于c# - 如何使用 WebClient DownloadStringAsync 来避免卡住 UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31632225/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com