Click here to Skip to main content
Click here to Skip to main content

Multi-threading and cross-thread function invoke

By , 9 May 2013
 

Introduction

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.

Steps

  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)
        Else
            DisplayError(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)
  7. In the background thread call the InvokeUIControl() function as required.
  8. Try
      // do something here that gives error
    Catch ex As Exception
      DisplayErrorOnUI(ex.Message)
    End Try

This will definitely help... Thanks.

License

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

About the Author

sisirp88
Software Developer
India India
Member
I love learning...

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberVikram.....9 May '13 - 4:50 
GeneralMy vote of 5professionalTadit Dash9 May '13 - 3:37 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130513.1 | Last Updated 9 May 2013
Article Copyright 2013 by sisirp88
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid