问题描述
这是莫名其妙的我,也许有人可以照到我的无知教育的光。这是一个C#Windows应用程序。我从一个线程访问列表框的内容。当我试图访问它像这样
prgAll.Maximum = lbFolders.SelectedItems.Count;
我得到的错误。然而,这里是部分我不明白。如果我注释掉线,非常下一行
的foreach(字符串目录中lbFolders.SelectedItems)
执行就好了。
编辑:像往常一样,我的沟通能力缺乏。让我澄清一下。
我知道,访问来自线程比他们对问题的原因进行了中创建的其它图形用户界面项目。我知道正确的方式来访问它们是通过委托。
我的问题主要是这样的:为什么我可以访问并遍历SelectedItems对象就好了,但是当我试图获得(未设置)它的Count属性,它吹了起来。
prgAll.Maximum = lbFolders.SelectedItems.Count;
在该行执行的任务(设置/添加),在默认情况下是不是线程安全的。
在第二行,它只是一个获得操作,其中线程安全只是无所谓。
编辑:我的意思不是访问prgAll元素
访问Count属性的更改内部状态列表框内收集的,这就是为什么它抛出异常。
This is baffling me, maybe somebody can shine the light of education on my ignorance. This is in a C# windows app. I am accessing the contents of a listbox from a thread. When I try to access it like this
prgAll.Maximum = lbFolders.SelectedItems.Count;
I get the error. However, here is the part I don't get. If I comment out that line, the very next line
foreach (string dir in lbFolders.SelectedItems)
executes just fine.
Edit:As usual, my communication skills are lacking. Let me clarify.
I know that accessing GUI items from threads other than the ones they were created on causes problems. I know the right way to access them is via delegate.
My question was mainly this:Why can I access and iterate through the SelectedItems object just fine, but when I try to get (not set) the Count property of it, it blows up.
prgAll.Maximum = lbFolders.SelectedItems.Count;
On that line you perform an assignment (set/add), which by default is not thread-safe.
On the second line it's just a get operation, where thread-safety merely doesn't matter.
EDIT: I don't mean access to the prgAll element.
Accessing the Count property changes the internal state of the ListBox inner collection, that is why it throws the exception.
这篇关于为什么会出现这样的错误:"跨线程操作无效:从它创建一个线程比其他线程访问控制lbFolders"?。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!