c# 出现堆栈溢出错误,怎么解决??

yzpcomp 2011-02-13 01:31:30
我用一个线程来判断是否连接到某台电脑,运行不到几分钟就出现错误 An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll ,请问有什么方法可以解决这个问题呢?



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();

}
...全文
1017 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
微恒软件 2012-03-14
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 xingyuebuyu 的回复:]
C# code

void Listen()
{
while (true)
{
System.Threading.Thread.Sleep(100);


IPHostEntry ipHost = Dns.Resolve("192.168……
[/Quote]


这样写会报错的,
qldsrx 2011-02-13
  • 打赏
  • 举报
回复
递归问题,所有递归执行的内容是要存放在堆栈中的,递归结束前不会释放,因此你这样无限递归自然要报错,只能改成循环来无限执行。
None465465535 2011-02-13
  • 打赏
  • 举报
回复
无限递归了,一种方法是用while(true),另一种方法是Listen()改成new Thread(this.Listen).Start()
wuyq11 2011-02-13
  • 打赏
  • 举报
回复
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)
{}
xingyuebuyu 2011-02-13
  • 打赏
  • 举报
回复
        void Listen()
{
while (true)
{
System.Threading.Thread.Sleep(100);


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;

}

}


http://technet.microsoft.com/zh-cn/subscriptions/system.net.dns.resolve.aspx

http://technet.microsoft.com/zh-cn/subscriptions/ms143998.aspx
改成一个无限循环,不要用递归调用,需要加入异常处理
另外Dns.Resolve方法已过时,可换用Dns.GetHostEntry
lizhibin11 2011-02-13
  • 打赏
  • 举报
回复
用while代替递归

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧