c# 出现堆栈溢出错误,怎么解决??
我用一个线程来判断是否连接到某台电脑,运行不到几分钟就出现错误 An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll ,请问有什么方法可以解决这个问题呢?
- C# code
public Form1() { InitializeComponent(); System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(Listen)); thread.IsBackground = true; thread.Start(); /* online = new OnListen(Listen); this.BeginInvoke(online);*/ } System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse("192.168.0.74"); string str = string.Empty; public delegate void OnListen(); OnListen online; void Listen() { System.Threading.Thread.Sleep(100); // while (true) IPHostEntry ipHost = Dns.Resolve("192.168.0.74"); //运行一段时间后,这句出现问题 :An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll IPAddress ipAddr = ipHost.AddressList[0]; str = ipAddr.ToString(); //System.Net.Dns.GetHostByAddress(ipAddress).HostName.ToString(); if (str != "") { label1.Text = string.Format("已连接,{0}", DateTime.Now); } else { label1.Text = string.Format("断开连接,{0}", DateTime.Now); } str = null; Listen(); }
[解决办法]
SocketException
解析 hostName 时遇到错误。
已过时,用Dns.GetHostEntry
IPHostEntry myIpHostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAdress = myIpHostEntry.AddressList[0];
IPEndPoint serverAddr = new IPEndPoint(ipAdress, port);
server = new TcpListener(serverAddr);
server.Start();
while (true)
{}
[解决办法]
无限递归了,一种方法是用while(true),另一种方法是Listen()改成new Thread(this.Listen).Start()
[解决办法]
递归问题,所有递归执行的内容是要存放在堆栈中的,递归结束前不会释放,因此你这样无限递归自然要报错,只能改成循环来无限执行。