我正在使用后台工作程序来监听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,但没有真正发生。 dowork没有被取消。我仍然可以收到数据包。
答案 0 :(得分:3)
listener.Receive
阻止,直到收到数据。因此,您的取消根本不被承认。
你可以做的是使用BeginReceive
(并摆脱BackgroundWorker)或尝试使listener
成为一个类字段并在取消时将其处理掉。后者应该留下阻塞接收但有例外。好吧 - 或者在取消后自己向听众发送消息(显然也会唤醒接收者)。