Cross-thread operation not valid


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



If we try to access a control which is on main thread from a thread, we will get the above exception.


Solution
========
Use Delegate Functions to access the controls


Example
=======
Set the label's text value from the thread


Imports System.Threading

Public Class Form1

Dim updateThread As Thread
Dim updateThreadStart As New ThreadStart(AddressOf populateDataBase)
Dim CallWorkDone As New MethodInvoker(AddressOf Me.workDone)
Dim CallWorkFailure As New MethodInvoker(AddressOf Me.workFailure)

' This delegate enables asynchronous calls for setting
' the cursor type of the cursor.
Delegate Sub SetTextCallback(ByVal [text] As String)


Public Sub New()

'Start a thread
updateThread = New Thread(updateThreadStart)
updateThread.IsBackground = True
updateThread.Name = "UpdateThread"
bThreadRunning = True

updateThread.Start()
End Sub

Public Sub populateDataBase()

Dim strSql = "SELECT * FROM " & table
Dim dataAdapter As SqlDataAdapter = Nothing

myDataTable = New DataTable

Try
Dim cmd As New SqlCommand(strSql, Connection)

dataAdapter = New SqlDataAdapter(cmd)

'Thread Safe Proc
If Me.InvokeRequired Then
' It's on a different thread, so use Invoke.
Dim d As New SetTextCallback(AddressOf setText)
Me.Invoke(d, New Object() {"Loading........Please Wait"})
Else
' It's on the same thread, no need for Invoke.
lblStatus.Text = "Loading........Please Wait"

End If

dataAdapter.Fill(myDataTable)

dataAdapter.Dispose()

Catch ex As Exception
dataAdapter.Dispose()

' Make asynchronous function call to Form's thread.
Me.BeginInvoke(CallWorkFailure)
Exit Sub
End Try
'
' Make asynchronous function call to Form's thread.
'Call the Form's Thread
Me.BeginInvoke(CallWorkDone)

End Sub
Private Sub setText(Text as String)
Me.lblStatus.Text = Text
End Sub


End Class


Comments

Author: Mahesh Nagar21 Dec 2009 Member Level: Gold   Points : 0

Thanks for Soutions

Author: chrisy04 May 2010 Member Level: Bronze   Points : 0

Thanks for the solution



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: