C# 服务器套接字引发类型为 'system.stackoverflowexception' 的未处理异常发生在 system.drawing.dll

C# Server Socket raises an unhandled exception of type 'system.stackoverflowexception' occurred in system.drawing.dll

我正在尝试在服务器应用程序上接收一系列图片帧,并在开始时将它们显示在图片框中,程序运行完美,但 5 到 10 分钟后,取决于我发送帧的方式,我收到错误 "An unhandled exception of type 'System.WhosebugException' occurred in System.Drawing.dll" 我在服务器中的代码看起来像那样

public void ImgRecive()
    {                        
       try
       {
            tcp.Start();
            sock = tcp.AcceptSocket();
            ns = new NetworkStream(sock);
            pictureBox1.Image = Image.FromStream(ns);
            tcp.Stop();
            if (sock.Connected == true)
            {
                while (true) { ImgRecive(); }
            }
            ns.Flush();
        }
        catch (Exception exxx) { MessageBox.Show(exxx.Message); }
    }

我试过了
pictureBox1.Image.Dispose(); 我也试过把图片框去掉重新做一遍还是一样的问题

所以有解决问题的想法吗?

查看这篇文章: https://msdn.microsoft.com/en-us/library/w6sxk224.aspx

~剪断

A WhosebugException exception is thrown when the execution stack overflows by having too many nested method calls. Associated Tips Make sure you do not have an infinite loop or infinite recursion. Too many method calls is often indicative of a very deep or unbounded recursion.

此外,检查堆栈上是否有任何 objects/data 分配,如果可能,尝试进行堆分配。

我用 while 循环替换了递归,它对我有用 新代码是这样的

public void ImgRecive()
    {
        tcp.Start();
        sock = tcp.AcceptSocket();
        ns = new NetworkStream(sock);
        while (sock.Connected == true)
        {
            try
            {
                tcp.Start();
                sock = tcp.AcceptSocket();
                ns = new NetworkStream(sock);
                pictureBox1.Image = Image.FromStream(ns);
                tcp.Stop();
                ns.Flush();
            }
            catch (Exception exxx) { MessageBox.Show(exxx.Message); }
        }
    }

谢谢大家