views:

28

answers:

1

I have a very simple StopWatch application in Silverlight. I have the following private properties in my MainPage class: _StopPressed (bool), _TimeStart, _Elapsed (string). I also have a "Start" and "Stop" button.

The "Start" button calls a method called UpdateTime that constantly updates _ElapsedTime until _StopPressed is true. When I originally wrote it, UpdateTime would block the UI so I couldn't press the Stop button, so I updated my code to use System.Threading.ThreadPool.QueueUserWorkItem with my UpdateTime method so that it updates _Elapsed on a background thread. That works great at updating the value.

However, if I try to set the .Text value of my TextBlock from within UpdateTime(), I get an UnauthorizedAccessException that has to do with one thread accessing the data in another thread.

What do I need to do to avoid getting this exception and appropriately update the UI without blocking it?

A: 

Use a DispatcherTimer instead of a timer, works nearly exactly the same but is used for updating UI elements.