完全禁用VB.Net中的线程安全 [英] Completely disable thread safety in VB.Net

查看:158
本文介绍了完全禁用VB.Net中的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完全禁用带有的非法跨线程检查

I am trying to completely disable illegal crossthreads checking with

CheckForIllegalCrossThreadCalls = False

我意识到自己无法在具有多个WebBrowser控件的TabControl中拥有多个选项卡,并且无法同时更改所有选项卡中的GUI(实际上是WebBrowser控件),最终找到了这个选项.

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.

问题是我需要完全禁用CheckForIllegalCrossThreadCalls,但是即使我将其放入代码中,我也似乎遇到了跨线程错误.还有什么需要调整的东西吗?

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?

推荐答案

禁用CheckForIllegalCrossThreadCalls确实不是一个好主意.为什么不只是让代码成为线程安全的呢?

Disabling CheckForIllegalCrossThreadCalls is really not a good idea. Why don't you just make your code thread-safe instead?

实际上比很多人想象的要容易.您要做的是调用一个检查表单的InvokeRequired属性的方法.如果返回True,则该函数将调用自身,然后执行指定的任务.

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.

.NET 4.0或更高版本中,您的操作方式如下:

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

这是在 .NET 3.5或更低版本中执行的操作:

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


用法示例:

.NET 4.0或更高版本:

.NET 4.0 or higher:

'Thread-safely sets Label1's text.
InvokeIfRequired(Sub() Label1.Text = "Hello World!")

.NET 3.5或更低版本:

.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

这篇关于完全禁用VB.Net中的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆