我正在使用后台工作人员来监听 UDP,然后进行处理。当我点击button2时我想退出
public snmpmain()
{
InitializeComponent();
backsnmp = new BackgroundWorker();
backsnmp.DoWork += new DoWorkEventHandler(backsnmp_DoWork);
backsnmp.ProgressChanged += new ProgressChangedEventHandler
(backsnmp_ProgressChanged);
backsnmp.WorkerReportsProgress = true;
_startsnmp = true;
backsnmp.WorkerSupportsCancellation = true;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
this.backsnmp.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
/* it executes this when button2 is pressed but nothing happens. I can receive the UDP packets the dowork hasn't stopped*/
{
_startsnmp = false;
backsnmp.CancelAsync();
listBox1.Items.Add("SNMP Stopped");
}
void backsnmp_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
listBox1.Items.Add (e.UserState as String);
}
void backsnmp_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
listBox1.Items.Add("SNMP Stopped");
button2.Enabled = false;
button1.Enabled = true;
}
}
void backsnmp_DoWork(object sender, DoWorkEventArgs e)
{
backsnmp.ReportProgress(0, "Initializing SNMP Listener on Port:" + port + "...");
UdpClient listener = new UdpClient(port);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
while (true)
{
if (backsnmp.CancellationPending)
{
e.Cancel = true;
return;
}
Thread.Sleep(100);
backsnmp.ReportProgress(0, "Waiting for messages....");
packet = listener.Receive(ref groupEP); // When I press button2 it's right here
// do some work here
当我单击 button2 时,它会执行 button2_Click,但实际上什么也没发生。任务没有取消。我仍然可以收到数据包。