我使用线程打开服务器的套接字并以同步方式从服务器读取数据来实现TCP客户端 . 当行 String thisLine = aReadStream.ReadLine(); 阻塞因为没有数据要从套接字读取而我尝试执行 Thread.Abort 来杀死该线程(因为它在该ReadLine()上被阻塞)我希望能够捕获 ThreadAbortException BUT 我可以'吨 .
线程在 ReadLine() 上仍然被阻塞,并且没有被杀死 . 在我的线程中使用的代码下面 .
你知道为什么和我做错了什么以及如何解锁ReadLine()?
private void readSocket_andTriggerEvents()
{
TcpClient aClient = null;
try
{
aClient = new TcpClient();
aClient.Connect(_HOST, _PORT);
Trace.WriteLine("Socket Connected");
NetworkStream aStream = aClient.GetStream();
StreamReader aReadStream = new StreamReader(aStream);
int nTimes = 0;
while (this.isSocketThreadStarted)
{
String thisLine = aReadStream.ReadLine(); // when no data
// is available the application hangs here.
// Thread.Abort doesn't work!
}
}
catch (ThreadAbortException ex)
{
Trace.WriteLine("The Thread was brute-forced killed");
// I never come here!!
}
catch (SocketException ex)
{
Helper.ShowErrorMessage(ex);
}
finally{
aClient.Close();
Trace.WriteLine("socket closed");
}
}