如何在不阻止UI的情况下使用WebClients SYNCHRONOUS DownloadString函数?

时间:2015-07-25 22:06:24

标签: c# multithreading webclient synchronous downloadstring

我试图在一个单独的非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;
    }

1 个答案:

答案 0 :(得分:1)

虽然您可以简单地将async-await与异步WebClient.DownloadStringTaskAsync方法一起使用,但如果您真的必须使用同步WebClient.DownloadString方法(由于某种原因),则可以在单独的非ui上执行它线程,你仍然可以使用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));
    }
}