Tuesday, October 20, 2009

solution for .net exception(vs 2005):Cross-thread operation not valid: Control ‘Form1′ accessed from a thread other than the thread it was created on

simple solution:write the following line just above the line,which causes exception,

Control.CheckForIllegalCrossThreadCalls = false

Alternative method:
create a new thread and place the lines (that causes the exception) inside that thread. Suppose if the exception fires when you call the function 'mymethod()'
Insert the 'mymethod' inside the new thread as follows:

Dim mythread As System.Threading.Thread
mythread = New System.Threading.Thread(AddressOf myThreadFunction)
mythread.Start()

Sub myThreadFunction()
mythread()
End Sub

This will solves the problem!

If you are famililar with delegates in .net, you may also use the following advanced techniques for solving this issue. visitu the following links:
http://www.tek-tips.com/viewthread.cfm?qid=1107023&page=1
for more about multithreading:
http://msdn2.microsoft.com/en-us/library/ms951089.aspx
http://msdn2.microsoft.com/en-us/library/ms951109.aspx
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnforms/html/winforms01232003.asp?frame=true

Happy Programming

No comments:

Post a Comment