C# Windows IoT - 从任务更新 GUI

C# Windows IoT - Update GUI from task

我已经尝试了很多,但我无法找到如何从 Windows Universal App for [=] 上的 运行 任务更新 GUI 元素,例如 TextBlock.Text 29=] Raspberry 上的物联网。

有什么办法吗?

它应该在不停止的情况下完成 运行 任务。

根据一个答案,我试过这个:

Task t1 = new Task(() =>
        {
            while (1 == 1)
            {

                byte[] writeBuffer = { 0x41, 0x01, 0 }; // Buffer to write to mcp23017
                byte[] readBuffer = new byte[3]; // Buffer to read to mcp23017
                SpiDisplay.TransferFullDuplex(writeBuffer, readBuffer); // Send writeBuffer to mcp23017 and receive Results to readBuffer
                byte readBuffer2 = readBuffer[2]; // extract the correct result
                string output = Convert.ToString(readBuffer2, 2).PadLeft(8, '0'); // convert result to output Format

                // Update the frontend TextBlock status5 with result
                Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () =>
                {
                    // Your UI update code goes here!
                    status6.Text = output;
                });

            }
        });
        t1.Start(); 

但是我得到以下 2 个错误:

Error   CS0103  The name 'CoreDispatcherPriority' does not exist in the current context

CS4014  Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

我是不是用代码做错了什么?

我不确定你的问题出在哪里,我想可能是不同线程的问题。 尝试使用调度程序。您需要集成 Windows.UI.Core 命名空间:

using Windows.UI.Core;

这是您的电话(稍作修改即可开箱即用)。

private void DoIt()
        {

            Task t1 = new Task(async () =>
            {
                while (1 == 1)
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                        () =>
                                        {
                                            // Your UI update code goes here!
                                            status6.Text = "Hello" + DateTime.Now;
                                        });
                    await Task.Delay(1000);
                }
            });
            t1.Start();

        }  

小提示:while (1=1) 对我来说听起来像是一个无限循环。 另一个提示:我添加了 "await Task.Delay(1000);" 以在循环期间稍作休息。

另请查看有关调度程序的此答案。 Correct way to get the CoreDispatcher in a Windows Store app