RunWorkerCompleted在异步void Dowork事件之前触发

时间:2017-05-24 09:41:03

标签: c# backgroundworker

我正在使用背景工作者进行BLE RSSI等级测试。

我的问题是在DoWork完成操作之前,会立即触发RunWorkerCompleted事件。

大多数DoWork事件操作是创建广告观察者并等待来自蓝牙低功耗设备的信号。 信号电平将从主线程更新,结果处理将在后台工作人员处理。

这是我打电话给后台工作人员的时候:

 ...
  worker = new BackgroundWorker();
        worker.DoWork += callTestBLE;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        worker.RunWorkerAsync(RSSI_Label);
  }

事件处理程序:

private async void callTestBLE(object sender, DoWorkEventArgs e)
    {
            BluetoothLEAdvertisementWatcher watcher1 ;
            BluetoothLEAdvertisementFilter advertisementFilter1;
            int rssiRetries1 = RSSIRETRIES;
            RssiValue = "";

            advertisementFilter1 = new BluetoothLEAdvertisementFilter();
            try
            {
                advertisementFilter1.Advertisement.LocalName = myUswm.getAdvetrismentName();
                checkRSSI = true;
            }
            catch (Exception) { checkRSSI = false; return; }

            watcher1 = new BluetoothLEAdvertisementWatcher(advertisementFilter);
            watcher1.ScanningMode = BluetoothLEScanningMode.Active;
            watcher1.Received += OnAdvertisementReceived;
            // Wait 5 seconds to make sure the device is really out of range
            watcher1.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
            watcher1.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);

            try
            {
                watcher1.Start(); 
                await testBLEAsync();
                if (myUswm.getConnectionStatus() == DISCONNECTED)
                {
                    checkNextUUTClick(new object(), new RoutedEventArgs()); return;
                }
                for (int i = 0; i < 5; i++)
                {
                    // if (RssiSamplesNum <= 0 || --rssiRetries < 0)
                    if (RssiSamplesNum <= 0 || --rssiRetries1 < 0)
                    {
                        //serviceList.Clear();
                        watcher1.Stop();
                        rssiRetries1 = RSSIRETRIES;
                        RssiSamplesNum1 = numOfAdvertismentSamples;
                        break;
                    }
                    else
                    {
                       ((Label)e.Argument).Content = RssiValue;
                        /*RSSI_Label.Dispatcher.Invoke(new Action(() =>
                        { RSSI_Label.Content = RssiValue; }));*/
                    }
                    Thread.Sleep(2000);
                  }    
            }
    catch (Exception err) { }
    }

    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
       finalizeBleTest();
    }

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

此处asyncawait存在问题。 BackgroundWorker有点过时,不支持异步代码。因此,当您等待testBLEAsync调用时,callTestBLE方法结束,此时您调用了RunWorkerCompleted事件,而实际代码仍然在后台运行。

最简单的解决方案是从代码中完全删除async / await,一切都应该按预期工作,或者,您可以使用任务和任务延续重写代码。

答案 1 :(得分:0)

我同意BackgroundWorkerasync / await不兼容的其他答案。但是,我不同意最简单的解决方案是删除async以支持BackgroundWorker。 IMO,优越的解决方案(也导致更简单的代码)是删除BackgroundWorker,而不是async;具体来说,replace the outdated BackgroundWorker with the superior Task.Run

// `worker` is now `Task`.
await Task.Run(() => callTestBLE());
finalizeBleTest();

callTestBLE的签名为async Task,而非async void