title: Getting spontaneous exceptions with Windows 10 BLE API
body: <p>I'm pairing with a BLE device and querying all it's services &amp; characteristics in a small test console program</p>
  
  <p>Every now and then I get this error during the query process:</p>
  
  <pre><code>Scanning for BLE Devices with service 00008000-0000-1000-8000-0012345678
  Finding nearest device
  Connecting to MAC CC12345678CF
  Pairing...
    Waiting for DevicePairingResult result...
    Waiting for DevicePairingResult result...
  Getting info...
    Waiting for GattDeviceServicesResult result...
    Waiting for GattReadResult result...
    Waiting for GattCharacteristicsResult result...
    Async op has Error: System.InvalidOperationException A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
    Async op has Error: System.ObjectDisposedException The object has been closed. (Exception from HRESULT: 0x80000013)
    Async op has Error: System.ObjectDisposedException The object has been closed. (Exception from HRESULT: 0x80000013)
    Async op has Error: System.ObjectDisposedException The object has been closed. (Exception from HRESULT: 0x80000013)
  Unpairing...
  System.NullReferenceException: Object reference not set to an instance of an object.
     at UWPWrapper.BLE.DeviceLister.ListServices(GattDeviceService[] services, Int32 level) in UWPWrapper\UWPWrapper\BLE\DeviceLister.cs:line 96
  </code></pre>
  
  <p>Where that row is just the if-case here, but it seems to happen in the for loop and many other places.</p>
  
  <pre><code> var descResult = chr.GetDescriptorsAsync().Wait();
   if (descResult.Status != GattCommunicationStatus.Success)
   {
     sb.AppendLine($"{indent}    No descriptors: {descResult.Status}");
   }
  </code></pre>
  
  <p>It seems like the objects I'm accessing are being disposed while I'm using them, cause I get errors in really strange places evcen though I'm keeping references all the time.</p>
  
  <p>Other questions point to this (listening to GATTCharacteristics.ValueChanged events). Any idea how to work around this?</p>
  
  <p>FWIW, I'm writing a plain C# desktop app but using the WinRT API wrappers. It seems to work pretty well except for this issue.</p>