views:

123

answers:

2

Hello!

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

when I try to access the control's width on a method that handles an event it throws me the following exception:

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

Is this method running in another thread?

Thank you!

+2  A: 

An event runs on the thread that fired it. So if the event was fired on a different thread than the one that created the control, it runs in a different thread, yeah.

Maximilian Mayerl
+4  A: 

Yeah, controls cannot be accessed by threads that have not created them. Well, to be more accurate they can if you really want but you risk the application locking up "randomly" due to a deadlock.

To get around this problem use the Invoke() or BeginInvoke() methods to set a callback for the "UI Thread" to pick up.

e.g.

private void HandleSomeEvent(object sender, EventArgs e)
{
    if(textBox1.InvokeRequired)
    {
        textBox1.BeginInvoke(new EventHandler(HandleSomeEvent), new object[]{sender, e});
    }
    else
    {
        textBox1.Text = "WIN!";
    }
}
Quibblesome