Cross-thread operation not valid
Hello,
I'm having trouble trying to update the Form1's text, I've tried the next code, but it throws this exception:
Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
What am I doing wrong?
vb.net Code:
Private Sub PercentCompleted(ByVal progress As Integer) Handles PercentDone.Progress
Dim deleg As New ProgressDone(AddressOf UpdateProgress)
Me.ProgressBar1.Invoke(deleg, progress)
End Sub
Private Sub UpdateProgress(ByVal e As Object)
Me.ProgressBar1.Value = CInt(e)
Me.Text = CStr(e) & "% Completed"
End Sub
Thanks in advance!!
Re: Cross-thread operation not valid
try this:
vb Code:
Private Delegate Sub UpdateProgressCallback(ByVal e As Object)
Private Sub UpdateProgress(ByVal e As Object)
If ProgressBar1.InvokeRequired Then
ProgressBar1.Invoke(New UpdateProgressCallback(AddressOf UpdateProgress),e)
Else
If me.InvokeRequired Then
me.Invoke(New UpdateProgressCallback(AddressOf UpdateProgress),e)
Else
Me.ProgressBar1.Value = CInt(e)
Me.Text = CStr(e) & "% Completed"
end if
end if
End Sub
Re: Cross-thread operation not valid
Hey Paul,
thanks for the fast reply. The progressbar invoke is working great, but it still gives me the Form1 error. (It does change Form1's text, but then it throws the error).
I have no idea of what it could be.
Re: Cross-thread operation not valid
try invoking the form too
Re: Cross-thread operation not valid
It's telling me to refer to it as Me, instead of Form1.
I'm trying this:
vb.net Code:
Private Sub PercentCompleted(ByVal e As Integer) Handles PercentDone.Progress
If Me.ProgressBar1.InvokeRequired Then
Me.ProgressBar1.Invoke(New UpdateProgressCallBack(AddressOf PercentCompleted), e)
Else
If Me.InvokeRequired Then
Me.Invoke(New UpdateProgressCallBack(AddressOf PercentCompleted), e)
Else
If Form1.InvokeRequired Then
Form1.Invoke(New UpdateProgressCallBack(AddressOf PercentCompleted), e)
End If
Me.ProgressBar1.Value = e
Me.Text = CStr(e) & "% Completed"
End If
End If
End Sub
Re: Cross-thread operation not valid
Why not use a Background Worker...or is that not possible? That would help handle any of your Cross-Threading problems, but I assume you've already tried that path?
Re: Cross-thread operation not valid
The reason why I'm not using a BW is because the process is being done by a class, so I had the class raise an event to report the progress and then I would report it the old-fashioned way.
Re: Cross-thread operation not valid
Oho, that explains why then. I have nothing else to contribute unfortunately :(.