Completely disable thread safety in VB.Net

不打扰是莪最后的温柔 提交于 2019-12-25 19:39:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!