下面的例子是一个windows窗体;该表单包含一个按钮,其 Click 事件连接到子例程:Button1_Click。
单击该按钮会导致创建 SomeClass (o),添加事件处理程序并开始工作。StartWork 将调用创建线程的匿名方法,使用另一个模拟工作的匿名方法,然后释放 (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