文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Silverlight 跨线程访问无效

Silverlight 跨线程访问无效

时间:2010-11-02  来源:imbob

原因分析:

在silverlight/wpf中只有创建 DispatcherObject 的线程才能访问该对象。例如,一个从主 UI 线程派生的后台线程不能更新在该 UI 线程上创建的内容

例如

private void button1_Click(object sender, RoutedEventArgs e)
{
    System.Threading.Thread thread=new System.Threading.Thread(()=>{
        ((Button)sender).Content = "Hello";
    });
    thread.Start();
    
}
解决办法有以下几种
1使用 SynchronizationContext;
此方法需要注意的是,System.Threading.SynchronizationContext.Current必须在UI线程中调用,如果在子线程中,将返回null;
private void button1_Click(object sender, RoutedEventArgs e)
{
    System.Threading.SynchronizationContext sc = System.Threading.SynchronizationContext.Current;
    System.Threading.Thread thread=new System.Threading.Thread(()=>{
        sc.Post((o) => {
            ((Button)sender).Content = "Hello";
        }, null);
       

    });
    thread.Start();
}
 
2 使用Dispatcher.BeginInvoke方法
private void button1_Click(object sender, RoutedEventArgs e)
{
   
    System.Threading.Thread thread=new System.Threading.Thread(()=>{

        this.Dispatcher.BeginInvoke(() => { ((Button)sender).Content = "Hello"; });
        
    });
    thread.Start();
}

3 使用BackgroundWorker 类来代替你的线程类
相关阅读 更多 +
排行榜 更多 +
西安交大通

西安交大通

生活实用 下载
长江云通

长江云通

生活实用 下载
translatez

translatez

生活实用 下载