UWP 的 HID 库崩溃

Crash of UWP's HID library

我正在开发一个 UWP 应用程序来使用 HID 设备。该应用程序几乎一直都在正常工作。但是当我关闭或 collapse/restore 时它经常崩溃。我遇到异常访问冲突阅读位置:

Exception thrown at 0x5FC8A31C (Windows.Devices.HumanInterfaceDevice.dll) in MyApp.exe: 0xC0000005: Access violation reading location 0x0000001E.

而且这个异常总是出现在CreateOutputReport方法上。

如何检查创建输出报告的可能性? 或者我如何在 UWP 中处理这个异常?

感谢您提前提出任何建议。

UPD:这是一个代码示例

HidDevice device = await HidDevice.FromIdAsync(id, FileAccessMode.ReadWrite);
if(device != null)
{
    var outReport = device.CreateOutputReport(); // Crashes here only on collapsing/closing
    byte[] buffer = new byte[(int)outReport.Data.Capacity];
    outReport.Data = buffer.AsBuffer();
    await device.SendOutputReportAsync(outReport);
}

UPD 2:从头开始测试。使用此代码创建 UWP 应用程序:

public async void StartSending()
{
    var devices = await DeviceInformation.FindAllAsync(HidDevice.GetDeviceSelector(usagePage, usageId, vid, pid));

    if (devices.Any())
    {
        var device = devices.FirstOrDefault();

        HidDevice hidDevice = await HidDevice.FromIdAsync(device.Id, FileAccessMode.ReadWrite);

        if (hidDevice != null)
        {
            while(true)
            {
                var outReport = hidDevice.CreateOutputReport();

                byte[] buffer = new byte[(int)outReport.Data.Capacity];

                // fill data

                outReport.Data = buffer.AsBuffer();
                await hidDevice.SendOutputReportAsync(outReport);

                await Task.Delay(500);
            }
        }
    }
}

在我折叠应用程序之前一切正常。恢复后应用程序失败。但这仅出现在已安装的应用程序上。它在 VS 中正常工作。

Video

感谢所有回复。 XavierXie 是对的,我对 suspending/resuming 没有任何逻辑。现在可以使用了。

代码如下:

Application.Current.Suspending += OnSuspending;
Application.Current.Resuming += OnResuming;

private void OnResuming(object sender, object e)
{
    // Reinitialize all watchers for HID
    // Subscribe to all necessary events
}

private void OnSuspending(object sender, SuspendingEventArgs e)
{
    // Remove all watchers for HID
    // Unsubscribe from all events
    // Dispose all active HID devices
}