<p>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<pre><code>prgAll.Maximum = lbFolders.SelectedItems.Count;</code></pre>
I get the error.  However, here is the part I don't get.  If I comment out that line, the very next line<pre><code>foreach (string dir in lbFolders.SelectedItems)</code></pre>
executes just fine.</p>

<p>Edit:
As usual, my communication skills are lacking.  Let me clarify.</p>

<p>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.</p>

<p>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.</p>

```
```
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.