我通过 TCP 与 IRC 服务器建立了连接。我用一个独立的任务读取了数据,到目前为止,一切都很好。但是,如果我想退出程序,我无法退出线程,因为它卡在 reader.ReadLine() 命令中(threadShouldRun 没有影响)。使用 Interrupt() 或 Abort() 似乎也不会改变任何内容。
要么我需要一种方法来确定何时有更多行需要读取,要么我需要强行终止线程(即使这很糟糕)。
private System.Threading.Thread myThread;
private bool threadShouldRun = true;
private StreamReader reader;
private void readStream()
{
while(threadShouldRun)
{
string line = reader.ReadLine();
if (line != null)
{
newLineEvent(this, new NewLineEventArgs(line));
}
}
}
最佳答案
使用异步调用(如此处所示的 BeginRead)并避免循环:
http://msdn.microsoft.com/en-us/library/system.io.stream.beginread.aspx
关于c# - 尝试中断卡在 reader.readLine() 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23964793/