【问题标题】:exception not caught in windows iot core applicationWindows iot 核心应用程序中未捕获异常
【发布时间】:2018-04-13 12:11:47
【问题描述】:

我正在开发在 rasberry pi3 上运行的 Windows iot 核心应用程序 我尝试使用以下方法从 azure iot hub 创建/获取设备密钥

public MainPage()
    {
        systemName = "RaspIot";
        this.InitializeComponent();

        /* Register for the unloaded event so we can clean up upon exit */
        Unloaded += MainPage_Unloaded;

        registryManager = RegistryManager.CreateFromConnectionString(connectionString);
        AddDeviceAsync().Wait();
    }

    private static async Task AddDeviceAsync()
    {
        Device device;

        try
        {
            device = await registryManager.AddDeviceAsync(new Device(systemName));
        }
        catch (DeviceAlreadyExistsException)
        {
            device = await registryManager.GetDeviceAsync(systemName);
        }

        deviceKey = device.Authentication.SymmetricKey.PrimaryKey;
    }

如果名称为“RaspIot”的设备已注册,则会引发异常。 这在 .net45 控制台应用程序中运行良好。但在 PI3 的 UWP 应用程序中,抛出异常(在调试时弹出)但未由 catch 捕获)。我应该怎么做?

【问题讨论】:

    标签: c# exception raspberry-pi3 windows-10-iot-core


    【解决方案1】:

    我可以重现您的问题。并且在使用您的代码运行 UWP 应用程序时,UI 挂起并且没有响应。因此,这不是 UWP 应用中的最佳实践。

    在 UWP 应用中,您可以直接使用AddDeviceAsync() 而无需Wait()。它会正常执行,并且可以捕获异常。

    但在控制台应用程序中,如果您删除 Wait() 运算符,应用程序将退出而不会完成任务。所以它们是不同的。

    要在 UWP 中调用异步 API,您可以参考 this document

    更新:

    并且不建议在MainPage函数中注册设备,因为每次启动应用程序都会执行它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-26
      • 2017-04-16
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      相关资源
      最近更新 更多