c# - 非用户界面 "The calling thread cannot access this object because a different thread owns it"

标签 c# .net wpf

我有以下代码:

var queue = printer.PrintQueue;
var canPrint = ! Dispatcher.CurrentDispatcher.Invoke(()
                            => queue.IsPaperJammed || queue.IsOutOfPaper || 
                               queue.IsInError || queue.HasPaperProblem);

它抛出以下错误:

The calling thread cannot access this object because a different thread owns it

我已经在 UI 线程上试过了(使用如上所示的调度器),我已经在当前线程上试过了(没有调度器)。

有没有办法询问哪个线程拥有它的对象?

最佳答案

你试过不使用 CurrentDispatcher 吗? :

var canPrint = ! Application.Current.Dispatcher.Invoke(()
                            => queue.IsPaperJammed || queue.IsOutOfPaper || 
                               queue.IsInError || queue.HasPaperProblem);

CurrentDispatcher.Invoke() 将从当前执行的线程调用您的代码,它是非 UI 线程,假设此问题中的片段是从非 UI 线程运行的。

引用资料:

关于c# - 非用户界面 "The calling thread cannot access this object because a different thread owns it",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22211845/

相关文章:

c# - "System.ArgumentException: ' 不存在从对象类型 Newtonsoft.Json.Linq.JValue 到已知托管提供程序 native 类型的映射。

c# - 在 ASP.NET 网站中正确使用文件设计器文件

c# - .NET 中的运算符重载

c# - 如何隐藏有关缺少列详细信息的行的 TreeListView 错误消息?

c# - 如何: Write a thread-safe method that may only be called once?

c# - 在 C# 中快速在屏幕上绘制各种形状/文本的轻量级方法?

c# - 扩展方法和通用约束的问题

c# - 为什么 http get 方法在 asp.net web api 中接受 http post 请求?

wpf - 运行时错误 : InverseBooleanConverter not found

wpf - 将生成的 ADO.Net DbContext 放入 View-Models 的最佳方法