退出线程阻塞在TCP在C#阅读 [英] Exiting a thread blocking on TCP read in C#

查看:431
本文介绍了退出线程阻塞在TCP在C#阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器/客户端启动一个新线程readerThread()用于读取传入TCP流量。阅读本线程块()。我怎样才能退出该readerThread()。

My server/client start a new thread "readerThread()" for reading incoming tcp traffic. This thread blocks on read(). How can i exit this readerThread().

的一种方法是启动另一个线程其关闭套接字当线程将要退出,以便读出将退出。有一个更清洁的/更好的方式来做到这一点。

One way is to start another thread which closes the socket when the thread is to be exited so the read would exit. is there a more cleaner/better way to do it.

推荐答案

我误解了这个问题。以下是我认为你应该做的。

I misunderstood the question. Here is what I think you should do.


  • 如果您创建了父线程插座,只有使用新的线程来读取输入的数据,那么我建议调用Socket.Shutdown()。这样的接收方法将返回0(无字节读),你可以从线程的方式退出。关机将禁用发送/接收,但如果在缓冲区中等待发送的任何数据/接收它将确保它被发送关闭套接字之前/接收。您Receive方法将返回0,如果你调用shutdown而插座被阻塞的接收,但它会抛出套接字错误代码=关机(或10058)套接字异常。所以,准备捕捉并处理它。

  • If you created the socket in parent thread, and only use the new thread to read incoming data, then I would suggest calling Socket.Shutdown().This way the Receive methods will return 0 (no bytes read), and you can exit from thread's method. Shutdown will disable send/receive, but if there is any data in buffer that is waiting to be sent/received it will ensure that it is sent/received before closing the socket. Your Receive method will return 0 if you call shutdown while the socket is blocked on Receive, but it will throw a socket exception with Socket error code = Shutdown (or 10058). So be ready to catch and handle it.

如果您在创建新线程的插座,其接受新的连接(Socket.Listen()和Socket.Accept),然后就可以与插座从父线程连接并发送0字节。你可以退出新线程接收方法时,返回0字节。

If you create the socket in new thread, and its accepting new connections (Socket.Listen() and Socket.Accept) then you can connect with that socket from your parent thread and Send 0 bytes. You can exit new thread when Receive methods returns 0 bytes.

如果您正在创建新的线程插座,它只能一个客户端(与其他插座连接),然后这不是一个好办法都没有。您可能不得不中止线程(不推荐),除非您配置服务器时,你希望你的客户端套接字关闭发送0字节,但这样一来你的客户端应用程序将依赖于服务器关闭套接字。

If you are creating the socket in new thread, and it can only a client (Connects with other socket) then this is not a good approach at all. You may have to Abort the thread (not recommended), unless you configure your server to send 0 bytes when you want your client socket to close, but this way your client app will be dependent on server for closing the socket.

这篇关于退出线程阻塞在TCP在C#阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆