Threading in .NET

If you have some trouble in updating GUI elements in .NET because they are not created by the thread just running, try the following:

delegate void onSensorChangeParameterDelegate(int index, int sensorValue);
void kit_OnSensorChange(int index, int sensorValue)
{
    if (InvokeRequired)
    {
        BeginInvoke(new onSensorChangeParameterDelegate(kit_OnSensorChange), new object[] { index, sensorValue });
        return;
    }
    txtInfo.Text = String.Format("Index={0}, Value={1}", index, sensorValue);
}

 

So the method is handed over to the GUI thread, where txtInfo is a TextField, and processed there. Jon has written a great article about threading in .NET and how it can be done.

Leave Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.