c# - 尝试中断卡在 reader.readLine() 中的线程

标签 c# .net multithreading streamreader irc

我通过 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/

相关文章:

c# - 如何扩展 C# 内置类型,如 String?

c# - 即使版本号错误,依赖程序集解析也会成功

asp.net - 我可以在与 .net 4.5 APS.net 站点相同的项目中使用 .net 4.61 类库吗?

c# - 寻求代码覆盖率和单元测试的建议

c# - 数据访问层的反射性能

c# - 打开dbf文件时出错: External table is not in expected format

c# - 如何使用 dispatchertimer 每 30 秒检查一次而不影响 c# 中的 UI?

multithreading - Haskell STM 并重试

java - 学习Java,为什么我没有得到一些线程的重叠?

c# - 当字符串中有反斜杠时,IndexOf 失败——为什么?