posted on Saturday, April 29, 2006 8:22 AM
by
bben
Update UI and InvokeRequired
Hey,
During a windows application developpement, I was interested in showing a bullet with a color (red/green) to inform the user that his/her computer is connected to the Internet.
So I plugged an event handler to swich between the bullets like follows:
[...]
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
[...]
delegate void SetStatus(bool status);
void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
bool isConnected = IsConnected();
if (InvokeRequired)
Invoke(new SetStatus(UpdateStatus), new object[] { isConnected });
else
UpdateStatus(isConnected);
}
void UpdateStatus(bool connected)
{
if (connected)
this.connectionPictureBox.ImageLocation = @"..\bullet.green.gif";
else
this.connectionPictureBox.ImageLocation = @"..\bullet.red.gif";
}
[...]
So I was obliged to use InvokeRequired (property of Control class) to distinguish between 2 cases:
- When the caller thread is not the same as the one the connectionPictureBox control was created on. In this case, you must call Invoke method.
- When threads are the same. No need to use Invoke method.
NET 2.0 brings some security since if you didn't use this pattern, you've got an exception, whereas in .NET 1.1, no exception is rised so your code seems to crash randomly.