C#Thread第二次不更改文本框值

时间:2016-04-08 01:08:09

标签: c# multithreading

我正在创建一个涉及使用线程的应用程序。一切正常,直到我第二次点击按钮。第二次单击按钮时没有任何反应。它就像第一次加载所有东西,然后只是锁定文本框的值。红色的东西只是无法显示的私人链接。它不是链接,因为它们第一次工作得很好。他们第二次不会工作。我希望我刚才所说的不是太混乱。

Image of my code

1 个答案:

答案 0 :(得分:1)

创建表单时

name1name2name3都已下载 ,当您按下时,它们只是绑定到文本框按钮第一次。

_name1()_name2()_name3()方法只是对象实例化,没有任何副作用(换句话说,它们不做任何事情)。

所有线程化的东西都只是松散的 - 你正在调用一些不做任何事情然后中止线程的方法(从而中止了一些无论如何都做不了的事情)。当代码当前被写入时,这对执行没有任何影响,即使在第一次执行时也是如此。

代码的简单同步修复将如下所示:

private void Button_Click(object sender, EventArgs e)
{
    using (WebClient client = new WebClient())
    {
        textBox1.Text = client.DownloadString("<your URL here>");
        textBox2.Text = client.DownloadString("<your URL here>");
        textBox3.Text = client.DownloadString("<your URL here>");
    }
}

看到你正在使用线程,你的目标显然是非阻塞,异步执行。在保留操作顺序的同时实现它的最简单方法是使用async/await

private async void Button_Click(object sender, EventArgs e)
{
    // Disabling the button ensures that it's not pressed
    // again while the first request is still in flight.
    materialRaisedButton1.Enabled = false;

    try
    {
        using (WebClient client = new WebClient())
        {
            // Execute async downloads in parallel:
            Task<string>[] parallelDownloads = new[] {
                client.DownloadStringTaskAsync("<your URL here>"),
                client.DownloadStringTaskAsync("<your URL here>"),
                client.DownloadStringTaskAsync("<your URL here>")
            };

            // Collect results.
            string[] results = await Task.WhenAll(parallelDownloads);

            // Update all textboxes at the same time.
            textBox1.Text = results[0];
            textBox2.Text = results[1];
            textBox3.Text = results[2];
        }
    }
    finally
    {
        materialRaisedButton1.Enabled = true;
    }
}