c# How to terminate a socket?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I want to listen for incoming socket connections on a thread. When I call MySocket.BeginAccept or MySocket.Accept, I cannot figure out how to stop the thread. Is there no way to stop the Socket Accept?
 
Define a public variabl mbol_Shutdown. Next when you are ready to shut the
socket down, assign the global mbol_Shutdown variable to True and signal the
System.Threading.ManualResetEvent "mobj_ListenResetEvent"
(mobj_ListenResetEvent.Set()). This should allow you to break out of the
loop.

While True
mobj_ListenResetEvent.Reset()
mobj_Socket.BeginAccept(New AsyncCallback(AddressOf
AcceptCallback), mobj_Socket)
mobj_ListenResetEvent.WaitOne()
If mbol_Shutdown then Exit While
End While

'clean up

Dennis said:
I want to listen for incoming socket connections on a thread. When I call
MySocket.BeginAccept or MySocket.Accept, I cannot figure out how to stop the
thread. Is there no way to stop the Socket Accept?
 
Bryan Martin said:
Define a public variabl mbol_Shutdown. Next when you are ready to shut the
socket down, assign the global mbol_Shutdown variable to True and signal the
System.Threading.ManualResetEvent "mobj_ListenResetEvent"
(mobj_ListenResetEvent.Set()). This should allow you to break out of the
loop.

While True
mobj_ListenResetEvent.Reset()
mobj_Socket.BeginAccept(New AsyncCallback(AddressOf
AcceptCallback), mobj_Socket)
mobj_ListenResetEvent.WaitOne()
If mbol_Shutdown then Exit While
End While

'clean up

Slightly cleaner would be to make the while construct *itself* test the
flag. However, you should also synchronize access to the flag to make
sure you don't just get a cached version each iteration. You could do
that by making the flag volatile, or by setting/reading a property
which contains a lock.
 
Back
Top