Withevents work AddHandler dont?

V

Vemund Halvorsen

Hi,

Im having some trouble getting Addhandler to work. Using withevents
everything is working fine. But with AddHandler I get no callback.

The code below works fin if I declare _tcp as a private class member (etc.
Dim WithEvents mTcp as New MyTCP). Classes/modules; module Main, class
MyCtrl and class MyTcp.

Any tips why using AddHandler dont work?

/Vemund


Adding handler (from MyCtrl):
---
Dim _tcp As New MyTcp
_tcp.Init(ip, port)
AddHandler _tcp.OnDataArrival, AddressOf TcpHandler
---

Handler (from MyCtrl):
---
Public Sub TcpHandler(ByVal data As String)
RaiseEvent OnDataArrival(data)
End Sub
---

Rasing event (from MyTcp):
---
Public Sub ReadHandler(ByVal asyncResult As IAsyncResult)
Dim data As String = String.Empty
Dim bytes As Int32 = mNetStream.EndRead(asyncResult)
data = Encoding.ASCII.GetString(mReadbuffer, 0, bytes)
Console.WriteLine("Received: {0}", Data)
RaiseEvent OnDataArrival(data)
Dim result As IAsyncResult = mNetStream.BeginRead(mReadbuffer, 0,
mReadbuffer.Length, ReadCallback, Nothing)
End Sub
---
 
M

Marina Levit [MVP]

Perhaps by the time you attach the handler, the event has aleady fired? Does
Init raise the event initially? Try adding the handler first, then calling
Init.
 
C

Claes Bergefall

Vemund Halvorsen said:
Hi,

Im having some trouble getting Addhandler to work. Using withevents
everything is working fine. But with AddHandler I get no callback.

The code below works fin if I declare _tcp as a private class member (etc.
Dim WithEvents mTcp as New MyTCP). Classes/modules; module Main, class
MyCtrl and class MyTcp.

Any tips why using AddHandler dont work?

/Vemund


Adding handler (from MyCtrl):
---
Dim _tcp As New MyTcp
_tcp.Init(ip, port)
AddHandler _tcp.OnDataArrival, AddressOf TcpHandler
---

Sounds to me like the _tcp variable goes out of scope (at which point the
event handler is implicitly removed) before the event is fired. You don't
need the WithEvents keyword btw, unless you attach event handlers by using
the Handles keyword. Simply declare you _tcp variable as a private clas
member like this:
Private _tcp As New MyTCP


/claes
 
V

Vemund Halvorsen

Any tips why using AddHandler dont work?

Found the problem. I hade declared a ManualResetEvent object with WaitOne
inside the _tcp object. This blocks the thread. But when I use WithEvents
keyword it works (strange!).

I removed the ManualResetEvent object and everything works perfect - also
when I add the handler using AddHandler dynamically.

/Vemund
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top