【问题标题】:Thread Error while updating UI by calling method from IOT Hub通过从 IOT Hub 调用方法更新 UI 时出现线程错误
【发布时间】:2018-06-06 09:32:00
【问题描述】:

我对 C# 和 Azure IoT 很陌生。也许我遇到的问题很容易解决。我想通过调用云中的方法来更新 UI 元素。但我收到以下错误:

应用程序调用了一个接口,该接口被编组为 不同的线程。 (来自 HRESULT 的异常:0x8001010E (RPC_E_WRONG_THREAD))

我知道这与 UI 在另一个线程中运行的事实有关。但我没有找到任何解决方案。

这里是代码

public sealed partial class MainPage : Page
{

    DeviceClient deviceClient;

    public MainPage()
    {
        this.InitializeComponent();
        deviceClient = DeviceClient.CreateFromConnectionString(GlobalConstant.DEVICE_CONNECTION_STRING, TransportType.Mqtt);
        deviceClient.SetMethodHandlerAsync("UpdateTextfield", UpdateTextfield, null);
    }

    private void updateTextField ()
    {
        IncomingMessage.Text = "Update";
    }

    private Task<MethodResponse> UpdateTextfield(MethodRequest methodRequest, object userContext)
    {
        updateTextField();
        string result = "{\"result\":\"Executed direct method: " + methodRequest.Name + "\"}";
        return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
    }
}

【问题讨论】:

  • 没有操作系统允许您从另一个线程修改 UI。在使用 MVVM 或只是数据绑定的 XAML/WPF/UWP 应用程序中,您无论如何都不需要。您不要直接修改控件。控件绑定到属性并在属性被修改并引发 PropertyChanged 事件时更新
  • 无论如何,您都可以使用IProgress&lt;T&gt; 接口从后台线程报告进度或任何其他消息,如[在异步 API 中启用进度和取消](在异步 API 中启用进度和取消)所示
  • @quallenbezwinger 回复是否解决了您的问题或仍有问题?

标签: c# azure asynchronous iot azure-iot-hub


【解决方案1】:

您调用的进程: IncomingMessage.Text = "Update"; 发生在非 UI 线程的线程上。您需要将线程从当前执行线程编组到 UI 线程。

Windows.UI.Core.CoreDispatcher 可以用于此。这是一个例子:

    using Windows.ApplicationModel.Core;

    private async void updateTextField ()
    {
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, ()=>{
            IncomingMessage.Text = "Update";
        });    
    }

交叉引用:“Run code on UI thread in WinRT

【讨论】:

  • 我不熟悉WPF/UWP,但是将dispatcher的赋值放在async void updateTextField方法中会更好吗? GetForCurrentThread 在这里,我们需要确保 current 确实是我们想要的。
  • @DannyChen 你是对的。谢谢。我更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-10
  • 2020-12-29
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多