Example Code

Update UI in Seperate Thread Using VB and Measurement Studio

Code and Documents

Attachment

Introduction

In visual basic if you would like to do more than one thing at once you must create a new thread (something LabVIEW does automatically).The problem is that you cannot update any User Interface elements from a thread different from the thread that spawned the elements in the first place due to security restrictions.

So if you want to update the UI from a background thread, you must use the Invoke command to piggyback the UI changes onto the main thread which has permissions to modify the UI.  Such a call can look like this

        If Me.TextBox1.InvokeRequired Then
            ' It's on a different thread, so use Invoke.
            Dim d As New SetTextCallback(AddressOf SetText)
            Me.Invoke(d, New Object() {[NewText] + " (Invoke)"})
        Else
            ' It's on the same thread, no need for Invoke.
            Me.TextBox1.Text = [NewText] + " (No Invoke)"
        End If

This is a common design pattern and more information about it can be found here: http://msdn.microsoft.com/en-us/library/ms171728.aspx

This example shows how you can update a TextBox from two seperate threads as described in the MSDN tutorial. In addition It uses a timer to update a chart in a seperate thread and you can show and hide multiple graphs without the UI freezing or blocking.

2010-01-04_122203.jpg

Steps to Complete

Download and run the attached VB 2003 With Measurment Studio 8.6 example.

Richard S -- National Instruments -- (former) Applications Engineer -- Data Acquisition with TestStand

Example code from the Example Code Exchange in the NI Community is licensed with the MIT license.

Comments
SomeGreatAliasGoesHere
Member
Member
on

I'm using NIMS 2010 SP1 and Visual Studio 2010 SP1.  The sample doesn't run even after I update references.  Therefore, the sample is useless unitl NI updates it.  So why isn't it up to date?  It's 2012.  All samples should have a version for each platform version.  All samples should be under automatic review at NI when new platform versions are released.  If needed, another sample should be created for the current platform version while maintaining availability of older samples for those still using the older platform versions.  Thanks, Andy.

Contributors