【问题标题】:C# Windows IoT - Update GUI from taskC# Windows IoT - 从任务更新 GUI
【发布时间】:2015-08-03 08:56:50
【问题描述】:

我已经尝试了很多,但我不知道如何更新 GUI 元素,例如从树莓上 Windows IoT 的 Windows 通用应用程序上运行的任务中更新 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.

我在使用代码时做错了吗?

【问题讨论】:

  • 我对 Windows-universal 没有经验,但在 winforms/wpf 中有一个 Invoke 方法可以做到这一点。以及异步版本 (InvokeAsync/BeginInvoke)。
  • 我已经尝试过调用它,但它没有在通用 Windows 应用程序下运行。
  • CS0103:使用 Windows.UI.Core 添加(参见下面的编辑示例) CS4014:添加 await 关键字并标记范围异步(参见下面的编辑示例)

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


【解决方案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

【讨论】:

  • 感谢您的帮助,我已尝试使用您提供的代码,但它不起作用(我已在问题中添加了代码)。
猜你喜欢
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 2015-11-07
相关资源
最近更新 更多