Update a TextBlock with elapsed time causing an UnauthorizedAccessException
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?
Use a DispatcherTimer instead of a timer, works nearly exactly the same but is used for updating UI elements.
精彩评论