silverlight中大部分的数据都是通过异步得到的,当得到了数据直接赋给UI的时候,容易出现“跨线程访问无效”错误。

例如:给UI的listbox控件设置数据源:

this.Posts.ItemsSource = blog.Posts;

注意blog.Posts是异步得到的一个数据源,这时就会出现“跨线程访问无效”错误。

解决方法:

if (this.Posts.Dispatcher.CheckAccess())
{
       this.Posts.ItemsSource = blog.Posts;

}
 else
{
       this.Posts.Dispatcher.BeginInvoke(() => { this.Posts.ItemsSource = blog.Posts; });
 }

posted on 2011-05-21 15:06  aparche  阅读(1754)  评论(1编辑  收藏  举报