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开发者_如何学JAVA.Visible = true;) saying:
Control.Invoke must be used to interact with controls created on a separate thread.
What's happening?
Your two ListBoxes were created on different threads. That is, in almost all cases, a really, really bad idea.
The reason why is there are 2 ListBox
references in this scenario
- listBox1
- 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.
精彩评论