Silverlight background thread to measure height

梦想的初衷 提交于 2019-12-24 11:55:59

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/1710721/silverlight-background-thread-to-measure-height

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!