我试着在一个单独的非ui线程上下载一个字符串,当它下载完成后更新ui,但我想在不冻结ui的情况下做这件事,所以我试着做一个线程,但这不起作用,然后我试图在那个线程中做一个线程,但也不起作用,我如何调用downloadstring函数而不冻结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;
}发布于 2015-07-26 10:17:32
尽管您可以简单地将async-await与异步WebClient.DownloadStringTaskAsync方法一起使用,但是如果您确实必须通过在单独的非UI线程上执行同步WebClient.DownloadString方法(由于某些原因)来使用它,那么您仍然可以非常简单地使用Task.Run()和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));
}
}https://stackoverflow.com/questions/31631603
复制相似问题