How to kill an asynchronous delegate?

S

Stewart

Hey Group,

Hoping someone can help me out. I have some code which starts up some
asynchronous code using a delegate. The code is below. Basically my
main code (not shown) calls ServerThreadStart.StartServer to start the
server running asynchronously. This works fine. Shouldn't be any
problems here.

My question is how can I get my code to kill this code running
asynchronously? There is a dlgtServer.Remove(Delegate, Delegate)
command but there seems to be little of value in MSDN to help you
determine the two parameters.

Hope you can help,

Stewart



Friend Delegate Sub ListenForConnectionDelegate(ByVal PortNo As Int16)

Friend Class ServerThreadStarter

Friend Shared Sub StartServer(ByVal PortNo As Int16)
Dim ar As IAsyncResult
Dim dlgtServer As New ListenForConnectionDelegate(AddressOf
ServerThread.ListenForConnection)

ar = dlgtServer.BeginInvoke(PortNo, AddressOf
CallbackFromServerThread, dlgtServer)

ar = Nothing
dlgtServer = Nothing
End Sub

Private Shared Sub CallbackFromServerThread(ByVal ar As
IAsyncResult)
' Retrieve the delegate
Dim dlgt As ListenForConnectionDelegate = CType(ar.AsyncState,
ListenForConnectionDelegate)
' Call EndInvoke
dlgt.EndInvoke(ar)
dlgt = Nothing
End Sub
End Class

Friend Class ServerThread
Friend Shared Sub ListenForConnection(ByVal PortNo As Int16)
...
End Sub
End Class
 
C

cecil

Stewart,
From the looks of what you are doing you would be better off using
the Thread class to spawn your worker thread. By using a delegate's
BeginInvoke method you are making use of a thread from the thread pool.
This method of multithreading is optimized for shorter running tasks
and has no built in way to allow you to kill the thread. I am sure it
could be done, but it would be a hack. If you use the Thread class you
have much greater control including the ability to kill the thread.
The method you start the thread with can not take any methods so remove
portno from the args of your listen method and make it a private field
of the class that is set in the constructor and make the listen method
an instance method instead of shared.

Hope this helps

Cecil Howell MCSD, MCAD.Net, MCT
 
W

windsurfing_stew

Thanks for your help. I've updated this code to work with the
Threading object rather than using delegates. Notice I've added a
StopServer method.

Friend Class ServerThreadStarter

Private Shared thrd As Thread

Friend Shared Sub StartServer(ByVal PortNo As Int16)
Dim svr As ServerThread

svr.PortNo = 8989
If thrd Is Nothing Then
thrd = New Thread(AddressOf svr.ListenForConnection)
thrd.Start()
End If
End Sub

Friend Shared Sub StopServer()
If Not thrd Is Nothing Then
thrd.Abort()
thrd.Join()
End If
End Sub

End Class
 

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

Top