调用线程无法访问此对象,因为不同的线程拥有它,即使使用调度程序也是如此

时间:2015-11-01 19:58:01

标签: c# wpf multithreading thread-safety dispatcher

我有一个Paragraph对象,我尝试从不同于创建的线程访问,在此处发布我的问题之前,我在网上搜索了一个解决方案,我找到了“Dispatcher”解决方案,但没有不知怎的,为我工作。

以下是代码:

Run r = new Run((string)name + Environment.NewLine);
r.Foreground = Brushes.Green;
Dispatcher.Invoke(new Action(() => { currentlyOnlineParagraph.Inlines.Add(r); }), DispatcherPriority.ContextIdle);

我收到此错误:

InvalidOperationException was unhandled
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: The calling thread cannot access this object because a different thread owns it.

screenshot

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

从我看到的几行代码中,我将尝试在图形线程上创建所有图形对象,包括Run对象:

Dispatcher.Invoke(new Action(() => {   
   Run r = new Run((string)name + Environment.NewLine);
   r.Foreground = Brushes.Green;
   currentlyOnlineParagraph.Inlines.Add(r);   
}), DispatcherPriority.ContextIdle);