In many cases your routines may need to update the UI and because of this your application will wag it's bony finger at you with: "Cross-thread operation not valid: ..."
While tempting, you really should avoid the CheckforillegalCrossThreadCalls = True on your form(s) to force your program to ignore illegal cross thread calls. Doing so may well cause you lots of pain down the road. Instead I've become a fan of a relatively simple strategy.
To safely update the UI from another thread a delegate is required. When I run into the need for this I create a delegate directly above the sub or function that will be called from outside the UI thread (with the background worker for example).
FYI - all code you put into the form, or call directly from the form will run in the same thread as the UI - thus potentially slowing down your UI.
The delegate will look something like this:
Expand|Select|Wrap|Line Numbers
- Private Delegate Sub del_MySub(MyArgument as MyType)
Now, inside the sub (or function) I test the call to see if it is necessary to employ the delegate. It looks something like this:
Expand|Select|Wrap|Line Numbers
- Private Sub MySub(MyArgument as MyType)
- If MyUIControl.InvokeRequired Then
- MyUIControl.Invoke(New del_MySub(AddressOf MySub), MyArgument)
- Else
- MyUIControl.Property = MyArgument
- End if
- End Sub
Expand|Select|Wrap|Line Numbers
- Private Delegate Sub del_MySub(MyArgument as MyType)
- Private Sub MySub(MyArgument as MyType)
- If MyUIControl.InvokeRequired Then
- MyUIControl.Invoke(New del_MySub(AddressOf MySub), MyArgument)
- Else
- MyUIControl.Property = MyArgument
- End if
- End Sub