C#Windows IoT - 从任务

时间:2015-08-03 08:56:51

标签: c# raspberry-pi task win-universal-app iot

我已经尝试了很多,但是我无法从Raspberry上Windows IoT的Windows通用应用程序上运行的任务中找到如何更新GUI元素,例如TextBlock.Text

有没有办法做到这一点?

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

根据答案,我试过这个:

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.

我使用代码做错了吗?

1 个答案:

答案 0 :(得分:1)

我不确定你的问题在哪里,我想这可能是不同线程的问题。 尝试使用调度程序。您需要集成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