在 Xamarin.Forms 中使用 Thread.Sleep

Using Thread.Sleep in Xamarin.Forms

我要执行以下

MainPage = new ContentPage
{
    Content = new StackLayout
    {
        Children =
        {
            new Button
            {
                Text = "Thread.Sleep",
                Command = new Command(() =>
                {
                    Thread.Sleep(1000);
                    MainPage.Animate("", x => MainPage.BackgroundColor = Color.FromRgb(x, x, x));
                }),
            },
            new Button
            {
                Text = "Task.Run + Thread.Sleep",
                Command = new Command(async () =>
                {
                    await Task.Run(() => Thread.Sleep(1000));
                    MainPage.Animate("", x => MainPage.BackgroundColor = Color.FromRgb(x, x, x));
                })
            },
            new Button
            {
                Text = "Device.StartTimer",
                Command = new Command(() => Device.StartTimer(
                    TimeSpan.FromSeconds(1),
                    () =>
                    {
                        MainPage.Animate("", x => MainPage.BackgroundColor = Color.FromRgb(x, x, x));
                        return false;
                    })),
            },
        }
    }
};

我包括了 System.ThreadingSystem.Threading.Tasks,但我仍然得到

The name 'Thread' does not exist in the current context.

This site表示Thread.Sleep可以用在Xamarin.Forms中。我在一个共享项目中有这个,而不是 PCL.

您可以尝试使用

await Task.Delay(milliseconds);

如果您想延迟线程。

要阻止你可以这样做

Task.Delay(TimeSpan.FromSeconds(5)).Wait();

如需稍等

异步:await Task.Delay(10000);

同步:Task.Delay(10000).Wait();

但请尽量避免阻塞 UI 线程,以确保良好的用户体验并保持您的应用响应迅速。

在Xamarin.Forms

中使用Thread.Sleep

有两个 Xamarin.Forms 模板:

  • Xamarin.Forms 便携式 Class 图书馆

    由于PCL子集机制,你没有机会得到Thread.Sleep

    2017 年更新: PCL 现在已弃用。如果你使用.netstandard 2.0,你可以使用Thread.Sleep,因为你已经习惯了。

  • Xamarin.Forms 共享项目

    此模板包含不支持 Thread.Sleep 的不同平台。 Windows UWP,Xamarin.Android 和 Xamarin.iOS 支持,Windows Phone 8.1,Windows 8.1 不支持。如果您 unload/delete 这 2 个项目,解决方案就会构建。 (不要忘记在 App.cs 中使用 System.Threading;)