Updating GUI (WPF) using a different thread
You can use Dispatcher.Invoke to update your GUI from a secondary thread.
Here is an example:
private void Window_Loaded(object sender, RoutedEventArgs e) { new Thread(DoSomething).Start(); } public void DoSomething() { for (int i = 0; i < 100000000; i++) { this.Dispatcher.Invoke(()=>{ textbox.Text=i.ToString(); }); } }
You may use a delegate to solve this issue.Here is an example that is showing how to update a textBox using diffrent thread
public delegate void UpdateTextCallback(string message);private void TestThread(){ for (int i = 0; i <= 1000000000; i++) { Thread.Sleep(1000); richTextBox1.Dispatcher.Invoke( new UpdateTextCallback(this.UpdateText), new object[] { i.ToString() } ); }}private void UpdateText(string message){ richTextBox1.AppendText(message + "\n");}private void button1_Click(object sender, RoutedEventArgs e){ Thread test = new Thread(new ThreadStart(TestThread)); test.Start();}
TestThread method is used by thread named test to update textBox
there.
I am also developing a serial port testing tool using WPF, and I'd like to share some experience of mine.
I think you should refactor your source code according to MVVM design pattern.
At the beginning, I met the same problem as you met, and I solved it using this code:
new Thread(() => { while (...) { SomeTextBox.Dispatcher.BeginInvoke((Action)(() => SomeTextBox.Text = ...)); }}).Start();
This works, but is too ugly.I have no idea how to refactor it, until I saw this:http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
This is a very kindly step-by-step MVVM tutorial for beginners.No shiny UI, no complex logic, only the basic of MVVM.