簡體   English   中英

C#線程第二次未更改文本框值

[英]C# Thread not changing the text box values the second time

我正在創建一個涉及使用線程的應用程序。 一切正常,直到我第二次單擊該按鈕。 第二次單擊該按鈕沒有任何反應。 就像第一次填充所有內容,然后僅鎖定文本框的值一樣。 紅色的內容只是無法顯示的私人鏈接。 它不是鏈接,因為它們在第一次就可以正常工作。 他們只是第二次不工作。 我希望我剛才所說的不會太混亂。

我的代碼的圖像

name1name2name3創建窗體時的所有下載的,他們只是必然要當你按下按鈕在第一時間文本框。

_name1()_name2()_name3()方法只是對象實例化,沒有任何副作用_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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM