C# VS2015 Changing from Forms to Universal Apps: Missing assembly 错误

C# VS2015 Changing from Forms to Universal Apps: Missing assembly error

我正在编写一个小程序来使用来自 Monobrick.dk 的单块 C# 库来控制 LEGO Mindstorms 汽车。我在 Windows Forms 中使用了该库,并且它有效。我听说表单是编写 Windows 应用程序的过时方式,所以我想切换到 Windows 通用平台。我编写了一些与工作代码类似的代码,但出现错误:

The type or namespace name 'Thread' does not exist in the namespace 'System.Threading' (are you missing an assembly reference?) App1 \App1\MainPage.xaml.cs 37

这很奇怪,因为表格 "System.Threading.Thread" 有效。

这是代码。它应该使电机 A 以半功率转动 3 秒。按下屏幕按钮后。

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    using MonoBrick.EV3;

    namespace App1
    {
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();

        }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        var ev3 = new Brick<Sensor, Sensor, Sensor, Sensor>("wifi");
        ev3.Connection.Open();
        ev3.MotorA.On(50);
        System.Threading.Thread.Sleep(3000);
        ev3.MotorA.Off();
           }
        }
    }

我在这里错过了什么? WUP 对初学者来说不是有点矫枉过正吗?也许我应该坚持使用 WPF?

非常感谢您的建议。

System.Threading.Thread 已从 Windows 运行时(支持通用 Windows 平台)中删除。相反,Microsoft 希望您专注于异步编程模式,而不是直接使用 Thread class(有关异步编程模式文档,请参阅 this page)。

正如 this question you should use the Task.Delay 方法中的回答,因此您的代码将变成以下几行:

private async void button_Click(object sender, RoutedEventArgs e)
{
    // code before
    await Task.Delay(3000);
    // code after
}

这有一个额外的好处,你 UI 不会变得无响应,因为 Thread.Sleep 方法会冻结 UI 线程,如果它没有在另一个线程或异步调用中执行.

您可能还想阅读 this article about asynchronous programming in C# and VB.NET