我正在用MSTest编写一些代码测试驱动开发风格的代码,围绕着Windows10蓝牙低能耗API。我有一个回调,当在扫描过程中发现BLE外围设备时,操作系统会调用该回调。
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();
}
如果我“运行选定的测试”,并且在回调中发生异常,则运行的进程不会明显地检测到它。测试通过,异常不会阻止被测单元正常运行。
[TestMethod]
async Task ScanTest()
{
StartScan();
await Task.Delay(10000);
// this always completes, even though I see the debug message in the Output
}
但是,如果我"Debug Selected Test",Visual Studio会像预期的那样警告我异常!
像BluetoothLEAdvertisementWatcher.Received这样的Windows API如何确定进程如何路由和捕获异常有什么“不同”之处吗?
该项目的目标是使用this trick访问UWP的.NET标准2.0。
发布于 2019-03-05 06:14:27
未在您的线程上引发ScanDiscovery事件。它是由通过调用_BleWatcher.Start()创建的线程引发的。因为它不是在与ScanTest()相同的线程上运行,所以您不能在那里捕获异常。
在调试模式下,无论异常在哪个线程上运行,Visual Studio都会在引发异常时停止。
您需要捕获ScanDiscovery内部的异常,或者查看AppDomain.UnhandledException之类的内容。
https://stackoverflow.com/questions/54895432
复制相似问题