Answer the question
In order to leave comments, you need to log in
How to organize the completion of a separately launched thread in C #, if the socket is listening to the network in it?
A separate thread is waiting for a message from the network. Everything works fine, but when you exit the program, the thread remains in memory.
// ...
while (Listening) {
Socket ChatSocketHandler = ChatSocketListener.Accept();
// ...
Answer the question
In order to leave comments, you need to log in
Try setting the IsBackground = true property for this thread so that it becomes a background thread and does not prevent the process from terminating.
The socket must be closed in another thread, then Accept will fall with an exception, which you will process.
Or, indeed, do it asynchronously through BeginAccept (http://msdn.microsoft.com/ru-ru/library/system.net.sockets.socket.beginaccept(v=vs.110).aspx), or, alternatively, create a client socket, and according to the action that you need (exit, as I understand it), make a connection and complete it ...
In principle, everything has already been stated above, I summarize:
There are two options as such:
1. Use APM and the BeginAccept method . The optimal choice. It can also be wrapped in TAP via wrapper and used with await.
2. Move the socket reference to the global space and leave the synchronous method in the thread. But when exiting, close or release the socket from another thread, and assign IsBackground to this thread (more details here ) so that even if the exit is incorrect, the thread does not hang.
Thank you all. I used the v_decadence (IsBackground = true) tip, since no processing is required when the thread ends:
Thread ListeningThread = new Thread(ListeningProcess);
ListeningThread.IsBackground = true;
ListeningThread.Start();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question