[英]C# Thread not changing the text box values the second time
name1
, name2
, name3
是創建窗體時的所有下載的,他們只是必然要當你按下按鈕在第一時間文本框。
_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.