调用线程无法访问此对象,因为不同的线程拥有它,即使在使用调度程序时
问题描述:
我有一个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.
我怎样才能解决这个问题?
答
从代码,我看到了几行字,我会尝试在图形线程上创建的所有图形对象,包括Run
对象:
Dispatcher.Invoke(new Action(() => {
Run r = new Run((string)name + Environment.NewLine);
r.Foreground = Brushes.Green;
currentlyOnlineParagraph.Inlines.Add(r);
}), DispatcherPriority.ContextIdle);
谢谢,它的工作! –
欢迎你。我很高兴它给出了修复 –