Addhandler Events inside a class


I have created a class which handles some information from a website. Inside this class I have URLConnection which gets the content from the website.
Here I have added addhandle to check the event “ContentReceived”. But it dosnt work. But if I write the same code in event, no problem

What am I doing wrong?

When asking a question it helps if you define the “doesn’t work” part as it can mean many things (didn’t compile. didn’t run, raised an exception). Also, if you can include code/errors it helps us see what you are seeing.

I think what you want is “AddHandler”, it should be used with a method that has the same return value and parameters PLUS “sender as <class_type>” as the first parameter.

In your case, you would have a property of URLConnection in your class called maybe “Connection as URLConnection”. You then need a method that will serve as the event handler called maybe “ConnectionContent”, this must-have the first parameter as the same type as the caller/sender.

ConnectionContent(sender as URLConnection, URL As String, HTTPStatus As Integer, content As String)

Now, in your classes’ constructor, you would create the URLConnection object via new and add its handler via Addhandler.

Connection = new URLConnection AddHandler Connection.ContentReceived, AddressOf ConnectionContent

Remember to clean up the handler when you are done with the same code but change AddHandler to RemoveHandler.

Have a look at AddHandler:

You are right.
It compiles ok, does not throw an error.
As far I can see in the debugger, it just dont call the event handler and run the code.

Here is the code inside the class:
Dim connect As New URLConnection
connect.Send(“GET”, “”)
AddHandler connect.ContentReceived, AddressOf ReceivedContent

The ReceivedContent method:
ReceivedContent(sender As URLConnection, Url As String, HTTPStatus As Integer, content As String)
variableContent = content

I then have a method to retrieve the variableContent to the main window.

This dosn´t work, I can see in the debugger that either the HTTPStatus or content variable is populated.

But if I use the code in the main window it works.

Hope it helps to pin point what I´m doing wrong better.

Ahh, you are using it as a local variable (dim creates a variable that disappears when it gets to the end of a method), When you call “connect.send” it is asynchronous and will continue to the end of the method. “connect” will go out of scope and be destroyed and the event will never be called. You should add “connect” as a property of your class, I would also add the handler before calling the send method.

I would never have thought of it running out of scope.
But now you are saying it, it is very obviously.
But still can´t get it to work right. So I work around it. Now I put it sync mode, instead of async, inside a thread. Works fine.

Thanks you very much Alex