c# - 在 Xamarin.Forms 中使用 Thread.Sleep

标签 c# xamarin xamarin.ios xamarin.forms sleep

我要执行以下操作

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(10000);

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

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

在 Xamarin.Forms 中使用 Thread.Sleep

有两个 Xamarin.Forms 模板:

  • Xamarin.Forms 可移植类库

    由于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 不支持。如果您卸载/删除这 2 个项目,则会生成解决方案。 (不要忘记在您的 App.cs 中使用 System.Threading;)

关于c# - 在 Xamarin.Forms 中使用 Thread.Sleep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35767643/

相关文章:

c# - 如何使用 asp.net 和 c# 从 Web 应用程序向手机发送短信?

c# - Xamarin 分步向导 android View

Xamarin 表单命令 CanExecute 不更新 Button IsEnabled

c# - 如何在 iOS mono 中禁用后退按钮

xamarin.ios - TinyIoC.TinyIoCResolutionException : Unable to resolve type: on ipad deployment 问题

ios - 在不创建新的 UICollectionView 的情况下更新 UICollectionViewFlowLayout?

c# - 在哪里可以找到 C# 的反锐化蒙版?

c# - SQL AZURE 中的设计联合

c# - SagePay 直接支付集成 C#

c# - 在 xamarin iOS 中 - 在 UITableViewCell 中获取 [indexPath.Row],使用按钮单击事件