views:

309

answers:

2

Hello!

I'm developing a Windows Mobile 5.0 and above application with .Net Compact Framework 2.0 SP2 and C#.

I have this code inside a method:

if (listBox1.InvokeRequired)
{
    Invoke(new MethodInvoker(
        delegate() { listaBox1 = listaBox2; listBox1.Visible = true; }));
}
else
{
    listBox1 = listBox2;
    listBox1.Visible = true;
}

When I run it, it throws an exception on second statement (listBox1.Visible = true;) saying:

Control.Invoke must be used to interact with controls created on a separate thread.

What's happening?

+1  A: 

The reason why is there are 2 ListBox references in this scenario

  1. listBox1
  2. listBox2

You only checked the InvokeRequired member for listBox1. Yet you actually end up calling .Visible on the instance originally pointed to by listBox2. Based on the resulting behavior, it's likely that the 2 references originally pointed to 2 different instances of ListBox.

To fix this, check the InvokeRequired on listBox2 since that's the one you actually end up using.

JaredPar
While I think you're basically right, this does not explain why listBox2 is on another thread than listBox1, since both seem to be part of the same form, which should be on a single thread. Can you create a control on a thread different from the parent's thread? This modifies the Controls property, after all...
OregonGhost
There is a thread that loads data to show it on listBox. The listboxes are custom controls. I've getting a lot of error messages (Control.Invoke must be used...) if I load data directly to listBox1. These is the reason why there are two listboxes.
VansFannel
@OregonGhost — yes, one can create controls on other threads and the rule is the same: all interaction with the control (excepting calling InvokeRequired) should be on the creating thread.
Paul Ruane
It requires some other condition to hold, for instance listBox1 was never shown.
Henk Holterman
+3  A: 

Your two ListBoxes were created on different threads. That is, in almost all cases, a really, really bad idea.

ctacke