C# Backgroundworker w/多个参数不取消

C# Backgroundworker w/ multiple parameters not cancelling

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

....
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();
        }
    }

}

但是工人并没有停下来。由于我在 worker 中使用的参数,它不起作用吗?

亲切的问候 巴斯蒂安

此致

在您的 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.

轻松地自己回答这个问题