V
V
Volodymyr S.2013-11-07 18:24:25
Multithreading
Volodymyr S., 2013-11-07 18:24:25

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();
// ...

Listening, of course, is changed to false to end processing, but it will only reach it on the next message from the network. And I need to interrupt ChatSocketListener.Accept() somehow.

Answer the question

In order to leave comments, you need to log in

7 answer(s)
V
Victor, 2013-11-07
@VYBGSS

Try setting the IsBackground = true property for this thread so that it becomes a background thread and does not prevent the process from terminating.

A
Antelle, 2013-11-07
@Antelle

The socket must be closed in another thread, then Accept will fall with an exception, which you will process.

A
Alexander Kouznetsov, 2013-11-07
@unconnected

AcceptAsync?

L
lexdevel, 2013-11-07
@lexdevel

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 ...

I
Illivion, 2013-11-08
@Illivion

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.

K
kosmos89, 2013-11-09
@kosmos89

Thread.Interrupt()?

V
Volodymyr S., 2013-11-08
@VYBGSS

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 question

Ask a Question

731 491 924 answers to any question