Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top