首页 > 解决方案 > UWP 的 HID 库崩溃

问题描述

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

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 中正常工作。

视频

标签: c#uwphid

解决方案


感谢所有回复。@XavierXie-MSFT 是对的,我没有任何暂停/恢复的逻辑。现在可以了。

这是代码:

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
}

推荐阅读