Click here to Skip to main content
13,247,816 members (62,503 online)
Click here to Skip to main content
Add your own
alternative version


6 bookmarked
Posted 9 May 2013

Multi-threading and cross-thread function invoke

, 9 May 2013
Rate this:
Please Sign up or sign in to vote.
Multi-threading and cross-thread function invoke.


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.


  1. Write a function that access the UI controls (here we are displaying error info of the background thread).
  2. Private Sub DisplayError(ByVal errMsg As String)
      lblMsg.Text = errMsg
  3. 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.
  4. private Sub DisplayErrorOnUI(ByVal errMsg As String)
        If (Me.InvokeRequired) Then
            Dim invokeDelegate As _invokeUIControlDelegate = _
                     New _invokeUIControlDelegate(AddressOf DisplayError)
            Me.Invoke(_invokeUIControlDelegate, errMsg)
  5. Declare a delegate in the class (or form in this case) to the above function (i.e., isplayErrorOnUI()).
  6. Private Delegate Sub _invokeUIControlDelegate(ByVal errMsg As String)
    </li />
  7. In the background thread call the InvokeUIControl() function as required.
  8. Try
      // do something here that gives error
    Catch ex As Exception
    End Try

This will definitely help... Thanks.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sisir Patro
Software Developer
India India
Learn the base not only the requirement related things for quick fixing and make others learn the exact thing always...

You may also be interested in...

Comments and Discussions

Suggestionif you prefer shorter way (only 4rows of code do the same :) ) Pin
Jaroslav Kadleček6-Nov-14 16:11
memberJaroslav Kadleček6-Nov-14 16:11 
GeneralMy vote of 1 Pin
Vikram.....9-May-13 5:50
memberVikram.....9-May-13 5:50 
GeneralMy vote of 5 Pin
Tadit Dash9-May-13 4:37
professionalTadit Dash9-May-13 4:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 9 May 2013
Article Copyright 2013 by Sisir Patro
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid