问题
I am trying to completely disable illegal crossthreads checking with
CheckForIllegalCrossThreadCalls = False
I ended up looking for this after i realized that i wasn't able to have multiple tabs in a TabControl with multiple WebBrowser controls and changing the GUI -the WebBrowser control actually- in all tabs at the same time.
The problem is that i need CheckForIllegalCrossThreadCalls to be completely disabled but it seems that i get a cross-thread error even if i put it in my code. Is there anything extra, like a setting or something that i should tweak?
回答1:
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
来源:https://stackoverflow.com/questions/37014810/completely-disable-thread-safety-in-vb-net