调用线程无法访问此对象,因为其他线程拥有它.WPF [英] The calling thread cannot access this object because a different thread owns it.WPF

查看:38
本文介绍了调用线程无法访问此对象,因为其他线程拥有它.WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我刷新标签时,我都会收到此错误:调用线程无法访问此对象,因为其他线程拥有它. 我尝试调用但它失败了.我正在使用 WPF 表单.

Whenever I refresh a label, I got this error: The calling thread cannot access this object because a different thread owns it. I tried to invoke but it's failed. I'm using WPF Form.

delegate void lostfocs(string st);
   private void imgPayment_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {

        Thread t = new Thread(modi);
        t.Start();
    }
 void modi()
    {
        try
        {
            label1.Content = "df";
        }
        catch
        {
            lostfocs ld = new lostfocs(up);
          //  ld.Invoke("df");
            object obj=new object();
            ld.Invoke("sdaf");
        }
    }
void up(string st)
    {
        label1.Content = st;
    }

推荐答案

使用 Dispatcher.Invoke 方法.

在线程上同步执行指定的委托调度员关联.

Executes the specified delegate synchronously on the thread the Dispatcher is associated with.

还有

在 WPF 中,只有创建 DispatcherObject 的线程可以访问那个对象.例如,一个 后台线程是从主 UI 线程无法更新 Button 的内容在 UI 线程上创建.为了让后台线程访问Button的Content属性,后台线程必须将工作委托给与 UI 线程关联的 Dispatcher.这是通过使用 Invoke 或 BeginInvoke 来完成的.调用是同步和 BeginInvoke 是异步的.该操作被添加到指定 DispatcherPriority 的 Dispatcher 事件队列.

In WPF, only the thread that created a DispatcherObject may access that object. For example, a background thread that is spun off from the main UI thread cannot update the contents of a Button that was created on the UI thread. In order for the background thread to access the Content property of the Button, the background thread must delegate the work to the Dispatcher associated with the UI thread. This is accomplished by using either Invoke or BeginInvoke. Invoke is synchronous and BeginInvoke is asynchronous. The operation is added to the event queue of the Dispatcher at the specified DispatcherPriority.

您收到错误是因为您的标签是在 UI 线程上创建的,而您正试图通过另一个线程修改其内容.这是您需要 Dispatcher.Invoke 的地方.

You are getting the error because your label is created on UI thread and you are trying to modify its content via another thread. This is where you would require Dispatcher.Invoke.

看看这篇文章WPF 线程使用 Dispatcher 构建响应更快的应用

这篇关于调用线程无法访问此对象,因为其他线程拥有它.WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆