C#Backgroundworker w /多个参数没有取消

时间:2015-11-10 19:36:52

标签: c# .net multithreading backgroundworker cancellation

我正在使用具有多个参数的后台工作者。 工作人员正在使用我的参数。 但我的问题是,我无法阻止背景工作者。

....
BackgroundWorker workerGetAdvData;
workerGetAdvData = new BackgroundWorker();
workerGetAdvData.DoWork += new DoWorkEventHandler(getAdvData.request_DoWork);

workerGetAdvData.RunWorkerAsync(clsComSettingMain); 

........


class ClsGetAdvData
{
    //open Serial Port with settings from clsComSettings class
    byte[] adv_request = { 0xF0, 0x02, 0x0D };   //Command for requesting advanced sensor data from PFC

public void request_DoWork(object sender, DoWorkEventArgs e)
{
    ClsComSettingMain clsComSettingMain = (ClsComSettingMain)e.Argument;
    string comPort = clsComSettingMain.comport;
    int baudRate = clsComSettingMain.baudRate;

    if (comPort != null && baudRate != 0)
    {
        SerialPort serialPort = new SerialPort(comPort, baudRate);
        serialPort.Open();

        while (true)
        {
            if (e.Cancel)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                serialPort.Write(adv_request, 0, 3); // Write byte array to serial port, with no offset, all 3 bytes
                Thread.Sleep(500);
            }
        }
    }

}

}

我尝试使用以下代码取消后台工作人员:

        private void MenuItem_Click_Serial_Stop(object sender, RoutedEventArgs e)
    {
        if (workerGetAdvData.IsBusy) //check if worker is running
        {
            workerGetAdvData.CancelAsync();
        }
    }

}

但工人不会停止。它不起作用,因为我在工人中使用的参数?

亲切的问候 巴斯蒂安

最好的问候

1 个答案:

答案 0 :(得分:2)

在您的DoWork代码中,您应该像这样检查BackgroundWorker.CancellationPending Property

public void request_DoWork(object sender, DoWorkEventArgs e)
{
    var worker = (BackgroundWorker)sender;
    ClsComSettingMain clsComSettingMain = (ClsComSettingMain)e.Argument;
    string comPort = clsComSettingMain.comport;
    int baudRate = clsComSettingMain.baudRate;

    if (comPort != null && baudRate != 0)
    {
        SerialPort serialPort = new SerialPort(comPort, baudRate);
        serialPort.Open();

        while (true)
        {
            if (worker.CancellationPending)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                serialPort.Write(adv_request, 0, 3); // Write byte array to serial port, with no offset, all 3 bytes
                Thread.Sleep(500);
            }
        }
    }

}

只需阅读CancelAsync方法documentation,您就可以轻松自己回答这个问题。