I have a particular problem with updating a TextBlock with changing values (which will eventually be streamed over a network). This is a similar problem to that experienced by others on this forum with the exception that the test solution below works initially (i.e the timer successfully updates the textBlock1.text which then displays correctly) but then fails after a certain number of iterations (usually between 200 and 300). I guess I am doing something wrong with whatever way I am handling the thread.
I am new to C#, .Net and threading so any advice would be greatly appreciated.
namespace TestWPF_WorkerThreads
{
MainWindow : Window
{
private int counter = 0;
private string counterText="";
public MainWindow()
{
InitializeComponent();
Timer myTimer = new Timer(Work, counterText, 1000, 100);
}
void Work(Object message)
{
counter++;
counterText = counter.ToString();
string temp = message.ToString();
temp = temp + counterText;
Thread.Sleep(100);
UpdateMessage(temp);
}
void UpdateMessage(string msg)
{
Action action = () => textBlock1.Text = msg;
Dispatcher.Invoke(action);
}
}
}
You have a timer with a period of 100 milliseconds, and the code which it invokes contains a ‘sleep’ which waits 100 milliseconds. This sounds wrong!
You should read this excellent article on timers on MSDN, you will see that the
System.Threading.Timerwhich you are using continues to fire regardless of whether you ‘sleep’. With WPF it is much better to use theDispatcherTimerclass which fires on the UI thread.