【发布时间】:2023-03-27 00:22:02
【问题描述】:
这里是代码,我已经在命令行应用程序中测试了 snmpconn 方法,但它在 Windows 窗体应用程序中运行时冻结,我没有理由吗?
public snmpmain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.button1.Click += new System.EventHandler(this.snmpconn);
}
private void button1_Click(object sender, EventArgs e)
{
//button1.Enabled = false; will disable the button before the event is fired
this.button1.Click += new System.EventHandler(this.snmpconn);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
int port = 162;
// UdpClient listener;
// IPEndPoint groupEP;
byte[] packet = new byte[1024];
int commlength, miblength, datatype, datalength, datastart, Objecttype, Objectlength;
int agent;
int timestamp;
int entrspc;
int specifictrap;
int finallen;
int objectstart;
string objectid;
string test1;
byte[] test2 = new byte[1024];
int temp;
string tempo;
private void snmpconn(object sender, System.EventArgs e)
{
listBox1.Items.Add("Initializing" + port + "...");
this.button1.Click -= new System.EventHandler(this.snmpconn);
UdpClient listener = new UdpClient(port);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
while (true)
{
listBox1.Items.Add("Waiting....");
packet = listener.Receive(ref groupEP);
listBox1.Items.Add("Processing...");
if (packet.Length != 0)
{ // do some work
}
}
}
这适用于命令行应用程序。
你有线索吗?
【问题讨论】:
-
抱歉,我不是来为您调试代码的。
-
如果您可以提供具体的错误消息、堆栈跟踪等,那么我们将能够为您提供更多帮助。将军“这是我的代码,怎么了?”问题没有得到很好的接受。所以通过调试器运行你的代码,看看会发生什么:)
-
问题是程序冻结,因此我认为没有错误消息....我建议您先检查
while (true)部分。 PS:我们应该只关注问题而不是规则...... -
如其他地方所述,
while (true)非常可怕,但在 windows 消息循环线程上尤其是坏消息,这可能解释了为什么您的控制台应用程序似乎可以工作。您的 Windows 应用程序无法继续处理 UI 事件,因为您已经永远占用了消息循环。