简体   繁体   中英

Why does my MSTest project only catch this exception when “Debug”d and not “Run”d?

I'm writing some code TDD-style with MSTest, around the Windows 10 Bluetooth Low Energy API. I have a callback that is invoked by the OS when a BLE Peripheral is discovered during Scanning.

void StartScan()
{
    _BleWatcher = new BluetoothLEAdvertisementWatcher();
    _BleWatcher.Received += ScanDiscovery;
    _BleWatcher.Start();
}

// this usually fires in under a second, and always in under ten seconds
void ScanDiscovery(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs bleAdvert)
{
    Debug.WriteLine("This handler was indeed called.");
    throw new Exception();
}

If I "Run Selected Test" and an exception occurs in the callback, it is not apparently detected by the running process. The test passes and the exception doesn't prevent the unit under test from otherwise running normally.

[TestMethod]
async Task ScanTest()
{
    StartScan();
    await Task.Delay(10000);
    // this always completes, even though I see the debug message in the Output
}

However, if I "Debug Selected Test", Visual Studio alerts me of the exception as expected!

Is there something "different" about how a Windows API like BluetoothLEAdvertisementWatcher.Received would determine how exceptions are routed and caught by a process?

The project is targeting .NET Standard 2.0, using this trick for accessing UWP APIs.

The ScanDiscovery event isn't being raised on your thread. It's being raised by the thread created by calling _BleWatcher.Start(). Since it's not running on the same thread as ScanTest() you can't catch the exception there.

In debug mode, Visual Studio will stop when the exception is thrown regardless of which thread it's running on.

You'll need to catch the exception inside ScanDiscovery or look into something like AppDomain.UnhandledException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM