【问题标题】:Failed to access XML Node in multi threaded WPF Application无法在多线程 WPF 应用程序中访问 XML 节点
【发布时间】:2017-12-11 10:40:22
【问题描述】:

我尝试从我的 WPF 应用程序中的不同线程访问 XMLNode 的属性。但是从不是 XMLDocument 的创建线程的线程的第一次访问会导致 System.InvalidOperationException 类型的异常。

详细说明:

调用线程无法访问该对象,因为不同的 线程拥有它。

这是我的代码

Monitor.Enter(lockAttribute); 

try 
{
    if (xmlInputNode.Attributes[sm_Attribute] != null) 
    {
        xmlInputNode.Attributes[sm_Attribute].InnerText = sm_AttributeValue.ToString();
    }
}

finally 
{
    Monitor.Exit(lockAttribute); 
}

我不明白这个例外。 XMLDocument 不是 WPF 控件,它具有 DependencyObject 和关联的 Dispatcher。

【问题讨论】:

  • 在 if(XML..) 上设置断点。它可能在工作线程上。这个错误说,你应该使用主线程。

标签: c# xml wpf multithreading


【解决方案1】:

试试这个:

Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
{
    if (xmlInputNode.Attributes[sm_Attribute] != null) 
    {
        xmlInputNode.Attributes[sm_Attribute].InnerText = sm_AttributeValue.ToString();
    }
}));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多