VB.NET RaiseEvent,线程安全? [英] VB.NET RaiseEvent, threadsafe?

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

问题描述

RaiseEvent 线程安全吗?

在 C# 中编写

if (event != null)
{
    event.invoke();
}

并且 C# 代码不是线程安全的....

and the C# code is not thread safe....

推荐答案

如果我需要做线程安全事件,我这样写:

If I need to do thread safe events, I write this:

Class Test

    Public Event Click(ByVal sender As Object, ByVal e As EventArgs)
    Public Event MouseIn(ByVal sender As Object, ByVal e As EventArgs)

    Private Delegate Sub EventArgsDelegate(ByVal e As EventArgs)
    Private ReadOnly _parent As Control

    Public Sub New(ByVal parent As Control)
        _parent = parent
    End Sub

    Private Sub OnClick(ByVal e As EventArgs)

        If _parent.InvokeRequired Then
            _parent.Invoke(New EventArgsDelegate(AddressOf OnClick), e)
        Else
            RaiseEvent Click(Me, e)
        End If

    End Sub

    Private Sub OnMouseIn(ByVal e As EventArgs)

        If _parent.InvokeRequired Then
            _parent.Invoke(New EventArgsDelegate(AddressOf OnMouseIn), e)
        Else
            RaiseEvent MouseIn(Me, e)
        End If

    End Sub

End Class

然后每当我需要引发事件时,我只使用 OnClick(new eventargs(...)) 等.如果您使用 Reflector 您可以观察到大多数线程安全控件都使用类似的系统.

Then whenever I need to raise the event I just use the OnClick(new eventargs(...)), etc. If you use Reflector you can observe that most thread safe controls use a similar system.

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

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