简体   繁体   中英

C# Thread not changing the text box values the second time

I am creating an application that involves using threads. Everything works until I click the button for the second time. Nothing happens on the second time the button is clicked. Its like the first time all the stuff loads and then just locks the values of the text boxes. The stuff in red is just private links that cannot be shown. Its not the links because they work just fine the first time. They just won't work the second time. I hope what I just said wasn't too confusing.

我的代码的图像

name1 , name2 , name3 are all downloaded when the form is created , they're just bound to the textboxes when you press the button the first time.

_name1() , _name2() , _name3() methods are just object instantiations and have no side effects of any kind (put differently, they don't do anything).

And all the threading stuff is just fluff - you're calling methods that don't do anything and then aborting the threads (thereby aborting something that isn't doing anything anyway). This has zero effect on the execution in any way as the code is currently written, even when executed the first time.

The simple, synchronous fix for your code will look like this:

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

Seeing as you're using threads, your goal is obviously non-blocking, asynchronous execution. The easiest way to achieve it while preserving the sequencing of operations is with 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM