在这些情况下,我只是从另一个线程结束流读取器。当您关闭阅读器时,它将打破循环。通过额外的同步队列只是不必要地做更多的样板。最终,您必须在某个地方停止阻塞阅读器。将值放入队列只会阻止您的消费者被阻止,但不会阻止您的读者。
这是一个套接字阻塞读取的示例。我将阻止读取 1 个我故意永远不会发送的字节。几秒钟后,我将处理套接字,套接字将退出其阻塞读取,应用程序将正常退出。我将记录每个线程正在做什么以及何时发生(每个日志行前面的数字是线程 ID,我将缩进单独的线程)。
在您使用阻塞阅读器的类中,您应该实现 Disposable 模式并在那里关闭/处置您的阅读器。
static void Main(string[] args)
{
SocketTest();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
public static void SocketTest()
{
int port = 22345;
var tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
// Listening thread
new Thread(() =>
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - Waiting for connection to port");
var socket = tcpListener.AcceptSocket();
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - Connection accepted");
var stream = new NetworkStream(socket);
var reader = new BinaryReader(stream);
try
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - Starting blocking read");
var bytes = reader.ReadBytes(1);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - Done blocking read, read {0} bytes", bytes.Length);
}
catch (Exception ex)
{
Console.WriteLine("Error reading " + ex);
}
}).Start();
// connecting thread
new Thread(() =>
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("\t" + Thread.CurrentThread.ManagedThreadId + " - Connecting to local port");
socket.Connect("127.0.0.1", port);
Console.WriteLine("\t" + Thread.CurrentThread.ManagedThreadId + " - Connecting to local succeeded");
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("\t" + Thread.CurrentThread.ManagedThreadId + " - Disposing of socket");
socket.Dispose();
}).Start();
Thread.Sleep(TimeSpan.FromSeconds(5));
}
当你运行它时,你会得到:
3 - Waiting for connection to port
4 - Connecting to local port
4 - Connecting to local succeeded
3 - Connection accepted
3 - Starting blocking read
4 - Disposing of socket
3 - Done blocking read, read 0 bytes
Press any key to exit
不过,您自己在这里回答了这个问题:
我的想法是让 removeServerResponseStream.Read 在另一个线程上
这正是你应该做的。当您知道您的应用程序已关闭时,请从活动线程关闭套接字。这个空闲是被阻塞的线程,你可以优雅地结束。
这里的模式是您通常为特定套接字启动一个线程,并维护一个活动线程,该线程是一种用于请求的“控制器”线程。