任务已计划并等待运行,但从未执行

时间:2019-09-27 08:52:31

标签: c# asynchronous task

我是C#异步编程的新手,并且某些异步方法存在问题。这些方法与外部蓝牙运动传感器通信。问题在于,在极少数情况下,相同的方法会等待从未运行的任务。

情况如下图所示。任务 MBientLab.MetaWear.Impl.MetaWearBoard.createRouteAsync()等待计划的任务完成。因此,该任务必须从 MBientLab.MetaWear.Impl.MetaWearBoard.createRouteAsync()任务中启动,该任务是所用API的一部分。

Currently running tasks

因此,正如我们所看到的,突出显示的行是已计划并等待运行的任务,但是无论我等待多长时间,它都保持该状态。它永远不会进入活动状态。其他任务正在等待突出显示的任务完成,因此一切都卡住了。

这是一个僵局,还是任务正在等待永远无法完成的任务?我有点困惑,我不知道如何解决这个问题。

编辑:我提取了导致问题的代码。它需要 using 语句中的块,Windows SDK和传感器才能正常工作。因此,您可能将无法运行它,但也许会有一些明显的错误。

// Nuggets
using MbientLab.MetaWear;
using MbientLab.MetaWear.Core;
using MbientLab.MetaWear.Data;
using MbientLab.MetaWear.Sensor;
using MbientLab.MetaWear.Win10;

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;

namespace MBientLabSensor
{
    public class MotionSensor
    {
        public List<double> GetX { get; } = new List<double>();
        public List<double> GetY { get; } = new List<double>();
        public List<double> GetZ { get; } = new List<double>();

        IMetaWearBoard _metawearDevice = null;

        // List of Bluetooth devices found after scanning
        private List<BluetoothLEDevice> DeviceList = new List<BluetoothLEDevice>();

        public async Task Connect(string MAC, int retries = 1)
        {
            if (_metawearDevice != null)
            {
                await StopAndDisconnectMotionSensor();
            }

            await ConnectToSensor(MAC.Trim(), retries);
        }

        public async Task StopAndDisconnectMotionSensor()
        {
            StopAccelerometer(_metawearDevice);
            await Disconnect(_metawearDevice);
        }

        public void StopAccelerometer(IMetaWearBoard _metawearDevice)
        {
            if (_metawearDevice == null)
            {
                throw new ArgumentNullException("The provided device is null!");
            }

            var acc = _metawearDevice.GetModule<IAccelerometer>();
            // Put accelerometer back into standby mode
            acc.Stop();
            // Stop accelerationi data
            acc.Acceleration.Stop();
        }

        public async virtual Task Disconnect(IMetaWearBoard _metawearDevice)
        {
            if (_metawearDevice == null)
            {
                throw new ArgumentNullException("The MetaWear device instance is null!");
            }

            _metawearDevice.TearDown();

            // Have the board terminate the BLE connection
            await _metawearDevice.GetModule<IDebug>().DisconnectAsync();
        }

        public async Task ConnectToSensor(string MAC, int retries = 3)
        {
            BluetoothLEDevice device = DeviceList.Find(x => ConvertToMAC(x.BluetoothAddress).Trim() == MAC.Trim());
            await AttemptConnect(device, retries);
        }

        private async Task AttemptConnect(BluetoothLEDevice BLEDevice, int retries)
        {
            _metawearDevice = await ConnectToDevice(BLEDevice, retries);

            if (_metawearDevice != null)
            {
                Task task = Task.Run(async () => await Setup(_metawearDevice));
                SetAccSamplingRate(_metawearDevice, 100f, 16f);
                StartAcc(_metawearDevice);
            }
        }

        public async Task Setup(IMetaWearBoard device, float connInterval = 7.5f)
        {
            if (device == null)
            {
                throw new ArgumentNullException("The provided device is null!");
            }

            // Set the connection interval
            await SetBLEConnectionInterval(device, connInterval);
            var acc = device.GetModule<IAccelerometer>();

            // Use data route framework to tell the MetaMotion to stream accelerometer data to the host device
            await acc.Acceleration.AddRouteAsync(source => source.Stream(data =>
            {
                // Clear buffers if there is too much data inside them
                if (GetX.Count > 1000)
                {
                    ClearSensorData();
                }

                // Buffer received data
                GetX.Add(data.Value<Acceleration>().X);
                GetY.Add(data.Value<Acceleration>().Y);
                GetZ.Add(data.Value<Acceleration>().Z);
            }));
        }

        public void ClearSensorData()
        {
            GetX.Clear();
            GetY.Clear();
            GetZ.Clear();
        }

        private async Task SetBLEConnectionInterval(IMetaWearBoard device, float maxConnInterval = 7.5f)
        {
            if (device == null)
            {
                throw new ArgumentNullException("The provided device is null!");
            }

            // Adjust the max connection interval
            device.GetModule<ISettings>()?.EditBleConnParams(maxConnInterval: maxConnInterval);
            await Task.Delay(1500);
        }

        public void SetAccSamplingRate(IMetaWearBoard device, float samplingRate = 100f, float dataRange = 16f)
        {
            if (device == null)
            {
                throw new ArgumentNullException("The provided device is null!");
            }

            var acc = device.GetModule<IAccelerometer>();
            // Set the data rate and data to the specified values or closest valid values
            acc.Configure(odr: samplingRate, range: dataRange);
        }

        public void StartAcc(IMetaWearBoard device)
        {
            if (device == null)
            {
                throw new ArgumentNullException("The provided device is null!");
            }

            var acc = device.GetModule<MbientLab.MetaWear.Sensor.IAccelerometer>();
            // Start the acceleration data
            acc.Acceleration.Start();
            // Put accelerometer in active mode
            acc.Start();
        }

        public async virtual Task<IMetaWearBoard> ConnectToDevice(BluetoothLEDevice device, int retries = 1)
        {
            _metawearDevice = Application.GetMetaWearBoard(device);

            if (_metawearDevice == null)
            {
                throw new ArgumentNullException("The MetaWear device is null!");
            }

            // How long the API should wait (in milliseconds) before a required response is received
            _metawearDevice.TimeForResponse = 5000;

            int x = retries;

            do
            {
                try
                {
                    await _metawearDevice.InitializeAsync();
                    retries = -1;
                }
                catch (Exception e)
                {
                    retries--;
                }
            } while (retries > 0);

            if (retries == 0)
            {
                return null;
            }
            else
            {
                return _metawearDevice;
            }
        }

        private string ConvertToMAC(ulong value)
        {
            string hexString = value.ToString("X");
            // Pad the hex string with zeros on the left until 12 nibbles (6 bytes) are present
            hexString = hexString.PadLeft(12, '0');
            return hexString.Insert(2, ":").Insert(5, ":").Insert(8, ":").Insert(11, ":").Insert(14, ":");
        }
    }
}

我使用

Task.Run(async () => await Connect(MAC, 3));

1 个答案:

答案 0 :(得分:1)

Task.Run()将您的代码包装到Task中。任务正在执行,但是您需要捕获任务执行的结果。因此,您需要这样做:

var task = Task.Run(async () => await Connect(MAC, 3));

await task;

但是这样做是没有意义的。如果要等待异步操作,只需执行以下操作:

await Connect(Mac, 3)