1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Events + Multi-Threading to Overcome Cross Thread Operation Error in VB.NET

Discussion in 'Visual Basic [VB]' started by ManzZup, Apr 21, 2011.

  1. ManzZup

    ManzZup New Member

    Joined:
    May 9, 2009
    Messages:
    278
    Likes Received:
    43
    Trophy Points:
    0
    Occupation:
    Production Manager:Software @ ZONTEK
    Location:
    Sri Lanka
    Home Page:
    Though VB is an object oriented language with multithreading I was always dissapointed with its less flexibility in using threads with the GUI. Of course many of you may have seen this InvalidOperationBlahException saying you cannot put up a progress bar/ timer./ count down iun a seperate thread while it interacts with the GUI. VB's solution was given as the background worker but I personally found it not-so-coordinate as well. So i thought of bringing up my own solutions. [Sure someother may have found it already but fot the sake of Googlers i'll continue with the tute :D]

    The solution i came up is using the high support given to the Events by VB.NET.

    Introduction



    Logic:
    1. Make a variable with encapsulation using the get/set methods.
    2. Raise an event if the variable is changed.
    3. Make the thread change the variable value as raise the event.
    4. Catch the event using the GUI.
    5. Function in the GUI will change the values [ex: progress] within the form so no cross thread calls.

    The Code



    Make a new project in VB.NEt and add a progressBar onto it and name it as " pbMain ".

    In Form1 add this code.

    Code:
    Public Class Form1
        Public Event VariableChange(ByVal val As Integer)
        Private Delegate Sub setProgressCallback(ByVal e As Integer)
        Public Property progress() As Integer
            Get
                Return progress
            End Get
            Set(ByVal value As Integer)
                RaiseEvent VariableChange(value)
            End Set
        End Property
        Public Sub progressChange(ByVal value As Integer)
            If pbMain.InvokeRequired Then
                Dim d As New setProgressCallback(AddressOf progressChange)
                Me.Invoke(d, New Object() {value})
            Else
                pbMain.Value = value
            End If
        End Sub
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            AddHandler VariableChange, AddressOf progressChange
    
            Dim t1 As New Threading.Thread(AddressOf threadAction)
            t1.Start()
    End Sub
    
        Sub threadAction()
            For i As Integer = 0 To 100 Step 1
                progress = i
                Threading.Thread.Sleep(200)
            Next
        End Sub
    End Class
    
    Lets go code by code,

    Code:
    Public Event VariableChange(ByVal val As Integer)
    
    Public Property progress() As Integer
            Get
                Return progress
            End Get
            Set(ByVal value As Integer)
                RaiseEvent VariableChange(value)
            End Set
        End Property 
    
    This makes a new event, as it names to fire up if a variable is changed.And the next block use Encapsulation like code for updating the the variable progress and note that in the Set method we raise the VariableChanged event.

    Code:
    AddHandler VariableChange, AddressOf progressChange
    
    Private Delegate Sub setProgressCallback(ByVal e As Integer)
    Public Sub progressChange(ByVal value As Integer)
            If pbMain.InvokeRequired Then
                Dim d As New setProgressCallback(AddressOf progressChange)
                Me.Invoke(d, New Object() {value})
            Else
                pbMain.Value = value
            End If
    End Sub
    
    Then in the form load we add a handler to handle the VaiableChanged Event if someone fired it. We direct the catching part to the progressChanged function and here's where the tricky part comes. In here we cannot just update the progressBar because they exists in separate threads, so we first check wheather it needed to be Invoked, if yes, we make a callBackRequest with the integer value we have back to the function, and this callBack calls the function as it is called by the Form1 thread or the main thread. So NO errors are given


    Then we just make this threadAction mwthod to test the thing, it will update the progress variable value with an interval of 200 miliseconds. As the sleep() is given to the thread handling the progress, the main thread will work well without any hanging or stuff while the progress is updated.

    THAT'S IT :D, by this mean you can add MANY THREADS so your customers will think your program is SUPER-FAST. This is juz a basic implementation but you can develop it into anything.

    Hope ya'll enjoy threads :) cyah all

    Visit my blog for more
     

Share This Page