title: Task is scheduled and waiting to run but never executed
body: <p>I am new to asynchronous programming in C# and I'm having issues with some async methods. Those methods communicate with an external Bluetooth motion sensor. The problem is that, in some rare cases, the same method waits for a task that is never ran. </p>
  
  <p>The situation is in the image below. The task <em>MBientLab.MetaWear.Impl.MetaWearBoard.createRouteAsync()</em> waits for the scheduled task to complete. So that task must be started from within the <em>MBientLab.MetaWear.Impl.MetaWearBoard.createRouteAsync()</em> task, which is part of the used API.</p>
  
  <p><a href="https://i.stack.imgur.com/cBWqf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cBWqf.jpg" alt="Currently running tasks"></a></p>
  
  <p>So as we can see, the highlighted line is a task that is scheduled and waiting to run, but it remains in that state no matter how long I wait. It never gets into active state. The other tasks are waiting for the highlighted task to complete, so everything is stuck. </p>
  
  <p>Can this be a deadlock, or could it be that the task waiting for something that will never complete? I'm a bit confused and I don't know how to approach this problem.</p>
  
  <p>EDIT: I extracted the code that causes the problems. It needs the nuggets from the <em>using</em> statements, Windows SDK and the sensor to work. So you probably won't be able to run it, but maybe there are some obvious mistakes.</p>
  
  <pre><code>// 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&lt;double&gt; GetX { get; } = new List&lt;double&gt;();
          public List&lt;double&gt; GetY { get; } = new List&lt;double&gt;();
          public List&lt;double&gt; GetZ { get; } = new List&lt;double&gt;();
  
          IMetaWearBoard _metawearDevice = null;
  
          // List of Bluetooth devices found after scanning
          private List&lt;BluetoothLEDevice&gt; DeviceList = new List&lt;BluetoothLEDevice&gt;();
  
          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&lt;IAccelerometer&gt;();
              // 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&lt;IDebug&gt;().DisconnectAsync();
          }
  
          public async Task ConnectToSensor(string MAC, int retries = 3)
          {
              BluetoothLEDevice device = DeviceList.Find(x =&gt; 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 () =&gt; 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&lt;IAccelerometer&gt;();
  
              // Use data route framework to tell the MetaMotion to stream accelerometer data to the host device
              await acc.Acceleration.AddRouteAsync(source =&gt; source.Stream(data =&gt;
              {
                  // Clear buffers if there is too much data inside them
                  if (GetX.Count &gt; 1000)
                  {
                      ClearSensorData();
                  }
  
                  // Buffer received data
                  GetX.Add(data.Value&lt;Acceleration&gt;().X);
                  GetY.Add(data.Value&lt;Acceleration&gt;().Y);
                  GetZ.Add(data.Value&lt;Acceleration&gt;().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&lt;ISettings&gt;()?.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&lt;IAccelerometer&gt;();
              // 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&lt;MbientLab.MetaWear.Sensor.IAccelerometer&gt;();
              // Start the acceleration data
              acc.Acceleration.Start();
              // Put accelerometer in active mode
              acc.Start();
          }
  
          public async virtual Task&lt;IMetaWearBoard&gt; 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 &gt; 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, ":");
          }
      }
  }
  </code></pre>
  
  <p>I ran it using </p>
  
  <pre><code>Task.Run(async () =&gt; await Connect(MAC, 3));
  </code></pre>