Cross-thread operation not valid:Control 'Level1' accessed from a thread other than the thread it was created on.

Friday, April 27, 20120 comments


Introduction:
Here we will discuss about one InvalidOperationException, which i got while doing one Windows application. The exception was like "Cross-thread operation not valid:Control 'lbl_Status' accessed from a thread other than the thread it was created on.". The error I got while working with BackgroundWorker.

Description:
I got this exception while doing one windows Application demo.I used there one progressbar control, one level,One BackgroundWorker and two buttons.
I want to see that progressing of the progressbar in terms of percentage.
In the line Me.lbl_Status.Text = FormatPercent(i/m_CountTo, 2)  , i got the error.

I use the same level for showing the status like Completed,Cancelled and to show that progess interms of percentage.
Why i got this error because we are using a background worker and we are attempting to acess controls on different thread .

Vb.Net doesn,t allow talking to objects on another thread directly, so have to go indirectly through one intermediate called Delegate.
A Delegate helps to communicate to objects of a different thread.
so i added the following lines of code:

 ' The delegate
    Delegate Sub SetLabelText_Delegate(ByVal [Label] As Label, ByVal [text] As String)
        Private Sub SetLabelText_ThreadSafe(ByVal [Label] As Label, ByVal [text] As String)
       
        If [Label].InvokeRequired Then
            Dim MyDelegate As New SetLabelText_Delegate(AddressOf SetLabelText_ThreadSafe)
            Me.Invoke(MyDelegate, New Object() {[Label], [text]})
        Else
            [Label].Text = [text]
        End If
      
    End Sub
And another changes i made one Substitute like Previously i wrote  Me.Lbl_Status.Text = FormatPercent(i / m_CountTo, 2)
Now i mentioned instead of that line the new line as belows:

SetLabelText_ThreadSafe(Me.lbl_Status, FormatPercent(i / m_CountTo, 2))
So now my code was errorfree, it worked fine.....

I am sharing the Screenshot as below....

Share this article :

Post a Comment

 
Copyright © 2010. SharePointDotNet.com - All Rights Reserved
Template Created by Creating Website Published by Mas Template