R – Silverlight background thread to measure height

silverlight

Thread MeasureThread = new Thread(delegate()
{
  TextBlock tb = new TextBlock();
});
MeasureThread.Start();

This throws an invalid cross thread access exception, even though this particular TextBlock would never be added to the visual tree. I realize that I could probably wrap it with Dispatcher.BeginInvoke, but that seems to defeat the point of using a background thread. I wanted to use this textbox to calculate the height of some text, for 1000+ different texts. I was hoping to be able to do this calculation in a background thread.

Best Answer

Unfortunately you cannot do this. All changes to UIElements must occur on the UI-thread, regardless of whether or not any specific element is actually in the visual tree.

I presume the reason that you don't want to place this logic on the UI thread is that it would cause the UI to lock up while the calculation completes. One way around this is to do what you suggested; use Dispatcher.BeginInvoke. And rather than just invoking the calculation for 1000+ TextBlocks, you could invoke the calculation for a single TextBlock, and then when that completes, invoke the next, and so forth. You can also use DispatcherTimer to schedule when things occur. This way, you break up your single large calculation, so that the UI never freezes up completely; of course it will take a longer time for the calculation to complete, but you do it without locking up the UI thread for an extended period of time.

Related Topic