c# - 调用线程无法访问此对象,因为另一个线程拥有它。WPF

标签 c# .net wpf multithreading dispatcher

<分区>

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

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.

还有

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 的地方。

看看这篇文章 WPF Threads Build More Responsive Apps With The Dispatcher

关于c# - 调用线程无法访问此对象,因为另一个线程拥有它。WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10795948/

相关文章:

c# - .net核心无法连接到Postgres(Docker Compose)

c# - Dapper 使用存储过程将多行插入到两个表中

c# - 在 C++ 应用程序中使用 C# dll

c# - wpf 数据网格中的列大小调整

c# - 具有复杂抽象类型集合的 WCF 抽象基类未包含在服务响应中进行反序列化

c# - 是否有更短的方法来编写此 LINQ 构造?

c# - Coldfusion OpenXml 错误 : Could not load file or assembly 'DocumentFormat.OpenXml'

.net - 从 system::String 转换为 std::string

列表框项目上的 WPF 动画

c# - 列表框 WPF : change foreground color of SelectedItem and keep Material Design?