我要执行以下操作
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.Threading
和 System.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/