有趣的foreach问题 [英] Interesting foreach problem

查看:69
本文介绍了有趣的foreach问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用foreach语句删除主网格的子项。

当我这样做时,我得到以下运行时异常:

I am trying to use a foreach statement to remove the children of my main grid.
When I do this, I get the following runtime exception:

调用线程无法访问此对象,因为另一个线程拥有它。
The calling thread cannot access this object because a different thread owns it.





这是我的代码:



Here is my code:

List<DraggableCard> remove=new List<DraggableCard>();
                foreach (UIElement em in cont.Children)//This is where I get my exception
                {
                    if (em is DraggableCard)
                    {
                        var d = em as DraggableCard;
                        if (d.UID == str.Replace("REMOVE_CARD{", "").Replace("}", ""))
                            remove.Add(d);
                    }
                }
                foreach (DraggableCard d in remove)
                {
                    cont.Children.Remove(d);
                }





我不知道为什么会这样;任何帮助将不胜感激。



I don't know why this would happen; any help would be appreciated.

推荐答案

Quote:

在WPF中,只有创建DispatcherObject的线程可以访问该对象。例如,从主UI线程分离出来的后台线程无法更新在UI线程上创建的Button的内容。为了让后台线程访问Button的Content属性,后台线程必须将工作委托给与UI线程关联的Dispatcher。这是通过使用Invoke或BeginInvoke来完成的。 Invoke是同步的,Be​​ginInvoke是异步的。该操作将添加到Dispatcher的事件队列中指定的DispatcherPriority。

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.





尝试使用Dispatcher.Invoke运行代码,以便它在与UI相同的线程。



Try running your code using Dispatcher.Invoke so that it runs on the same thread as the UI.


这篇关于有趣的foreach问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆