此错误在子线程访问UI线程的时候出现,

原因分析:

在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 类来代替你的线程类

相关文章:

  • 2021-06-08
  • 2021-11-02
  • 2021-11-14
  • 2022-12-23
  • 2021-11-28
  • 2022-12-23
  • 2021-06-25
猜你喜欢
  • 2022-12-23
  • 2021-06-30
  • 2021-08-06
  • 2022-12-23
  • 2021-09-09
  • 2022-03-07
  • 2021-12-24
相关资源
相似解决方案