未处System.StackOverflowException 确保程序没有无限循环或无线递归
我想在form2点击一个按钮的时候form1显示form2隐藏,然后关闭form1的时候form2也同时关闭,而且窗体form1需要用到form2窗体中的client_Socket; server_Socket;,所以我在form1中声明了form2 的实例,可调试的时候出问题了
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace howareyou
{
public delegate void childcolose();
public partial class Form2 : Form
{
public Socket server_Socket;
public Socket client_Socket;
private Form1 game_form = new Form1();
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
game_form.closefather += new childcolose(this.closing);
this.Hide();
game_form.Show();
Thread lisetn = new Thread(new ThreadStart(ListenNow)); //开启监听线程
lisetn.IsBackground = true; //设置后台线程isbackground属性为true,确保主线程关闭时,后台线程同时关闭
lisetn.Start();
}
void closing()
{
this.Close();
}
private void ListenNow()
{
server_Socket =new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8090);
server_Socket.Bind(ipep);
server_Socket.Listen(10);
client_Socket = server_Socket.Accept();
}
private void button2_Click(object sender, EventArgs e)
{
IPAddress remoteIp;
try //如果输入的ip地址不合法,则会引发此异常
{
remoteIp = IPAddress.Parse(remIp.Text);
client_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(remoteIp, 8090);//远程主机ip和端口号
//客户端,不需要绑定
try
{
client_Socket.Connect(ipep); //连接服务器端,用于传送棋子坐标和文本消息
}
catch
{
MessageBox.Show("无法与远程主机取得连接,请检查ip地址是否正确或稍后再试!您也可以直接创建游戏!");
}
}
catch
{
MessageBox.Show("您输入的ip地址不正确!");
}
}
}
}
我在form1中的代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Windows.Forms;
namespace howareyou
{
public partial class Form1 : Form
{
private Form2 M_form = new Form2();
///////////////////////////
/////////////////////////
…………………………………
//////////////////////////
/////////////////////////
}
我在调试的时候程序在 private Form2 M_form = new Form2();发生错误,提示我 未处理 System.StackOverflowException
确保程序没有无限循环或无线递归,这是怎么回事?
[解决办法]
看看
form2中有 private Form1 game_form = new Form1();
form1中有 private Form2 M_form = new Form2();
这不循环才怪
[解决办法]
同意
[解决办法]
眼神不错。。。