声明委托用作lambdas强制转换异常

时间:2012-07-08 01:53:18

标签: vb.net delegates

使用lambda表达式是否会导致内存泄漏?

我正在尝试在sub中声明一个委托,并将其用作“一次性”事件处理程序,然后在触发后将其设置为空。像这样的事情:

Private Sub MySub()
    Dim o As SomeObject
    Dim d as System.Delegate = Sub()
                  'Do some stuff
                   d = Nothing
                End Sub
    AddHandler o.SomeEvent, d
End Sub

但是我在addhandler上遇到了一个无效的强制转换异常。但是这样可能/需要吗?

没有代码hilite我正在堆栈移动

1 个答案:

答案 0 :(得分:1)

以下示例是一个Windows窗体;表单包含一个按钮,其Click事件连接到子例程:Button1_Click。

单击该按钮将导致创建SomeClass(o),添加事件处理程序并开始工作。 StartWork将调用创建线程的Anonymous方法,使用另一个模拟工作的Anonymous方法然后释放(o)引用。

Public Class Form1
    Private Class SomeClass
        Public Event DoWork()

        Sub StartWork()
            RaiseEvent DoWork()
        End Sub
    End Class

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Debug.WriteLine("Button1_Click Started.")
        ' create class
        Dim o As New SomeClass()
        ' add handlers
        AddHandler o.DoWork, Sub()
                                 Debug.WriteLine("o.DoWork Event Handler Started.")
                                 ' threading
                                 Dim t As New Threading.Thread(Sub()
                                                                   Debug.WriteLine("Worker Thread Started.")
                                                                   ' simulate work (5 seconds)
                                                                   Threading.Thread.Sleep(5000)
                                                                   ' release reference
                                                                   o = Nothing
                                                                   Debug.WriteLine("Worker Thread Stopped.")
                                                               End Sub)
                                 t.Start()
                                 Debug.WriteLine("o.DoWork Event Handler Stopped.")
                             End Sub
        ' start the work
        o.StartWork()
        Debug.WriteLine("Button1_Click Stopped.")
    End Sub
End Class