使用VB .Net异步socket方法时,回调函数应该如何定义?
Private Sub ServerRunTime(Optional ByRef ListeningAddress As String = "", Optional ByRef Port As Short = 31337)
Dim Listener As Socket = ConfigListener(ListeningAddress, Port)
Listener.Listen(32)
Listener.BeginAccept(New AsyncCallback(AddressOf OnAccept), Listener)
End Sub
Private Sub OnAccept(ByVal AcceptResult As IAsyncResult)
Dim Listener As Socket = CType(AcceptResult.AsyncState, Socket)
Dim aClientObj As New ClientObj
Dim ClientID As Integer = Clients.Count
aClientObj.ClientSok = Listener.EndAccept(AcceptResult)
aClientObj.ClientID = ClientID
Clients.Add(aClientObj)
Clients(ClientID).ClientSok.BeginReceive(Clients(ClientID).RecvBuffer, 0, Clients(ClientID).RecvBuffer.Length, SocketFlags.None, AddressOf OnReceive, ClientID)
Listener.BeginAccept(New AsyncCallback(AddressOf OnAccept), Listener)
End Sub
在上面的代码示例中,我都测试了
New AsyncCallback(AddressOf OnReceive)
和
AddressOf OnReceive
并且都产生相同的结果。
那么哪个是正确的?是否可以将 AsyncCallback 对象创建为变量以避免每次接收都创建一个新对象?