1

我需要不断地监听来自我的 C# TCP 服务器的消息,所以我在单独的线程中进行:

private void StartMessageReceivingLoop()
{       
    new Thread(){
        public void run()
        {
            String msg = null;

            try
            {
                msg = inputStream.readLine(); // inputStream is a BufferedReader instance.
            } 
            catch (IOException e)
            {
                e.printStackTrace();
            }

            if (msg != null && msg != "")
                NotifyAndForwardMessage(msg); // Notify listeners about the message.

            run(); // Next iteration.
        }
    }.start();
}

我的方法有什么问题?为什么我会收到 StackOverflowError?我猜它run()的调用速度非常快,因为BufferedReader.readLine()它是非阻塞的,但我能做些什么呢?

4

1 回答 1

3

不要run()run(). 这不是递归函数。如果您想继续阅读直到某些条件,请将其包装在一个 while 循环中。通过在执行时调用您正在执行的方法,您正在创建另一个堆栈帧。你真正想要的只是循环。

public void run() {
   String msg = null;
   while(true) {  // Or whatever your exit condition is...
      try {
         msg = inputStream.readLine();
      } catch(IOException e) {
         // Handle properly.
      }
      if (msg != null && msg != "") {
          NotifyAndForwardMessage(msg);
      }
   }
}

为了帮助说明,它有点像这样......

Thread.start()
   + run() // 1 (called by thread)
      + run() // 2 (called by previous run)
         + run() //3 (called by previous run)
            +etc... where you'll eventually run out of stack space.
于 2015-01-04T22:43:56.023 回答