0

我正在使用后台工作人员来监听 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,但实际上什么也没发生。任务没有取消。我仍然可以收到数据包。

4

1 回答 1

3

listener.Receive阻塞直到接收到数据。因此,您的取消根本无法识别。

您可以做的是使用BeginReceive(并摆脱 BackgroundWorker)或尝试创建listener一个类字段并在取消时处理它。后者应该让阻塞接收异常。好吧 - 或者在取消后自己向听众发送一条消息(这显然也会唤醒接收者)。

于 2013-07-10T09:53:10.387 回答