Disabling CheckForIllegalCrossThreadCalls
is really not a good idea. Why don’t you just make your code thread-safe instead?
It’s actually easier than a lot think. What you have to do is call a method which checks the InvokeRequired
property of the form. If it returns True
, the function will invoke itself and then execute the specified task.
Here’s how you’d do it in .NET 4.0 or higher:
Public Sub InvokeIfRequired(ByVal Method As Action)
If Me.InvokeRequired = True Then '"Me" being the current form.
Me.Invoke(Sub() InvokeIfRequired(Method)) 'Invoke this method to make it thread-safe.
Else
Method.Invoke() 'Execute the specified method.
End If
End Sub
And here’s how you’d do it in .NET 3.5 or lower:
Delegate Sub InvocationDelegate(ByVal Method As Action)
Public Sub InvokeIfRequired(ByVal Method As Action)
If Me.InvokeRequired = True Then '"Me" being the current form.
Me.Invoke(New InvocationDelegate(AddressOf InvokeIfRequired), Method) 'Invoke this method to make it thread-safe.
Else
Method.Invoke() 'Execute the specified method.
End If
End Sub
Example usage:
.NET 4.0 or higher:
'Thread-safely sets Label1's text.
InvokeIfRequired(Sub() Label1.Text = "Hello World!")
.NET 3.5 or lower:
'Thread-safely sets Label1's text.
InvokeIfRequired(AddressOf SetNewText)
...further down in code...
Private Sub SetNewText()
Label1.Text = "Hello World!"
End Sub
solved Completely disable thread safety in VB.Net