我最近發表了一篇關於此的文章,但我認爲我的最後一個問題沒有寫得很好,我確實得到了答案,但我想看看是否有更簡單的解決方案,因爲我發現最後一個問題令人困惑。這次我試圖儘可能清楚地寫出它。新線程打開新窗口,如何在新窗口中更新文本框?
我這裏WPF應用程序下面的代碼是代碼MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
int index = i;
threads[i] = new Thread(new ThreadStart(test));
threads[i].SetApartmentState(ApartmentState.STA);
threads[i].IsBackground = true;
threads[i].Start();
}
}
public void test()
{
OutputWindow outputwindow = new OutputWindow();
outputwindow.Show();
System.Windows.Threading.Dispatcher.Run();
outputwindow.textBox1.Text = "writing";
//some more stuff done
//some more stuff done
//some more stuff done
outputwindow.textBox1.Text = "\nmore writing";
//some more stuff done
//some more stuff done
//some more stuff done
outputwindow.textBox1.Text = "\nmore writing";
}
我怎樣才能讓textBox1.Text真正得到更新測試()是
代碼正在執行?
問候!
編輯
謝謝您的回答,但我無法使它工作還沒有。
這是一個網絡應用程序,所以我認爲文本框比數據綁定更合適,因爲我想在整個程序中打印超時,ping和更多信息,以確保一切按計劃進行。
我試了一些你的答案,但我無法讓它工作。這是我試過的最後一個例子,它不起作用
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
int index = i;
threads[i] = new Thread(new ThreadStart(test));
threads[i].SetApartmentState(ApartmentState.STA);
threads[i].IsBackground = true;
threads[i].Start();
}
}
public void test()
{
OutputWindow outputwindow = new OutputWindow();
outputwindow.Show();
System.Windows.Threading.Dispatcher.Run();
outputwindow.textBox1.Text = "writing";
//some more stuff done
//some more stuff done
//some more stuff done
outputwindow.textBox1.Text = "\nmore writing";
//some more stuff done
//some more stuff done
//some more stuff done
Action action =() => outputwindow.textBox1.Text = "\nmore writing";
Dispatcher.Invoke(action);
}
欣賞它。非常感謝。 – Arya
有沒有辦法在窗戶關閉時使工作方法停止工作?現在我每秒用一次無限循環嘗試使用Console.beep(),即使關閉窗口,我仍然可以聽到蜂鳴聲。 – Arya
我開始使用製表符,它運行得更好 – Arya