我有以下应用程序结构中:更新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