我有以下應用程序結構中:更新UI線程
public partial class MainWindow : Window
{
// Methos to update the TextBlock
public void updateTextBlock(string txt)
{
this.myTextBlock.Text += txt;
}
private void startThreadBtn_Click(object sender, RoutedEventArgs e)
{
// Start Thread1 here
Thread1 thread1 = new Thread1();
new Thread(new ThreadStart(thread1.doSomthing)).Start();
}
}
class Thread1
{
public void doSomthing()
{
// ------------------------------
// Update myTextBlock from here
// ------------------------------
// Thread2 starts here
Thread2 thread2 = new Thread2();
new Thread(new ThreadStart(thread2.doSomthing)).Start();
}
}
class Thread2
{
public void doSomthing()
{
// ------------------------------
// Update myTextBlock from here
// ------------------------------
}
}
從這兩個線程Thread1
和Thread2
類的我想更新TextBlock
這是在MainWindow
。
我已經看到下面的解決方案,並沒有發現這個問題涵蓋在這個問題中,我也是初學者,發現它很難理解。
- How to update UI from another thread running in another class
- How to update the GUI from another thread in C#?
- Update UI from background Thread
我可以使用在Thread1
有關從Thread2
更新UI上述問題,但什麼提供的解決方案。
我正在使用.NET框架4.5。
做什麼是最好的方法。
這絕對是一樣的。 – Sinatr 2014-10-10 06:53:59
您可否指出解決方案。 – User7723337 2014-10-10 06:54:44
由於您在Window類中,因此可以使用Dispatcher。就像if(!Dispatcher.CheckAccess()){Dispatcher.BeingInvoker(...); }。不過,我會建議你看看TPL(任務並行庫)來啓動你的線程。由於您可以輕鬆地將任務鏈接在一起,並且使用SynchronizationContext在前景(UI)和後臺線程之間來回切換上下文,所以對於您所做的事情要好得多。 – kha 2014-10-10 06:57:54