If you have ever worked on a multithreaded application, you probably know that accessing controls of UI thread (like textbox, labels etcc...) directly from another thread is not possible . Acessing UI controls directly from a thread other than UI thread would give you a run-time error .
Here is the simple solution to access the UI controls from a background thread.
- Write a function that access the UI controls (here we are displaying error info of the background thread).
Private Sub DisplayError(ByVal errMsg As String)
lblMsg.Text = errMsg
- Write another function that decides if it is being called from the UI thread or from another thread- If its called from its own thread, call the
DisplayError() function directly or else invoke it through a delegate.
private Sub DisplayErrorOnUI(ByVal errMsg As String)
If (Me.InvokeRequired) Then
Dim invokeDelegate As _invokeUIControlDelegate = _
New _invokeUIControlDelegate(AddressOf DisplayError)
- Declare a delegate in the class (or form in this case) to the above function (i.e.,
Private Delegate Sub _invokeUIControlDelegate(ByVal errMsg As String)
- In the background thread call the
InvokeUIControl() function as required.
// do something here that gives error
Catch ex As Exception
This will definitely help... Thanks.