调用线程不能访问此对象,因为不同的线程拥有it.WPF线程、对象、不同、WPF

2023-09-02 11:54:14 作者:情话难免七分假

每当我刷新一个标签,我得到这个错误: 调用线程不能访问此对象,因为不同的线程拥有它的我试图调用,但它的失败。我使用WPF窗体。

 委托无效lostfocs(字符串ST);
   私人无效imgPayment_MouseLeftButtonDown(对象发件人,MouseButtonEventArgs E)
    {

        线程t =新主题(莫迪);
        t.Start();
    }
 无效莫迪()
    {
        尝试
        {
            label1.Content =DF;
        }
        抓住
        {
            lostfocs LD =新lostfocs(上);
          // ld.Invoke(东风);
            obj对象=新的对象();
            ld.Invoke(SDAF);
        }
    }
无效了(线St)
    {
        label1.Content = ST;
    }
 

解决方案

使用Dispatcher.Invoke方法。

  

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

此外

  WFP做的程序,调用线程无法访问此对象,因为另一个线程拥有该对象

在WPF中,只有创建DispatcherObject的线程可以访问   该对象。例如,后台线程是从剥离出来   主UI线程不能更新按钮后的内容   在UI线程上创建。为了让后台线程   访问Button的Content属性,后台线程必须   委派的UI线程相关的工作的调度。   这是通过使用Invoke或BeginInvoke来完成。调用是   同步和BeginInvoke是异步操作。该操作被添加到   调度程序在指定的DispatcherPriority事件队列。

您所得到的错误,因为你的标签UI线程上创建的,您正试图通过修改另一个线程的内容。这是在那里你会需要Dispatcher.Invoke。

看看这篇文章 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;
    }

解决方案

Use Dispatcher.Invoke Method.

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

Also

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.

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.

Check out this article WPF Threads Build More Responsive Apps With The Dispatcher

 
精彩推荐
图片推荐