问题描述
我要执行以下操作
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
,但我仍然得到
I included System.Threading
and System.Threading.Tasks
, but I still get
当前上下文中不存在名称线程".
本网站建议 Thread.Sleep
可以在 Xamarin.Forms
中使用.我在一个共享项目中使用了这个,而不是一个 PCL.
This site suggests that Thread.Sleep
can be used in Xamarin.Forms
. I have this in a shared project, not a PCL.
推荐答案
如果你想等
异步:await Task.Delay(10000);
同步:Task.Delay(10000).Wait();
但请尽量避免阻塞 UI 线程,以确保良好的用户体验并保持您的应用响应速度.
But please try to avoid blocking the UI thread to ensure a good user experience and keep your app responsive.
在 Xamarin.Forms 中使用 Thread.Sleep
有两个 Xamarin.Forms 模板:
There are two Xamarin.Forms templates:
Xamarin.Forms 可移植类库
Xamarin.Forms Portable Class Library
因为PCL子集机制,你没有机会获得Thread.Sleep
.
Because of the PCL subset mechanism, you have no chance to get Thread.Sleep
.
2017 年更新:PCL 现在已弃用.如果您使用 .netstandard 2.0,您可以按照习惯使用 Thread.Sleep
.
Update 2017: PCLs are deprecated, now. If you use .netstandard 2.0, you can use Thread.Sleep
as you are used to it.
Xamarin.Forms 共享项目
Xamarin.Forms Shared Project
此模板包含不支持 Thread.Sleep
的不同平台.Windows UWP、Xamarin.Android 和 Xamarin.iOS 支持它,Windows Phone 8.1 和 Windows 8.1 不支持.如果您卸载/删除这 2 个项目,则解决方案会生成.(不要忘记在 App.cs 中使用 System.Threading;)
This Template contains different platforms that do not support Thread.Sleep
. Windows UWP, Xamarin.Android and Xamarin.iOS support it, Windows Phone 8.1, and Windows 8.1 not. If you unload/delete the 2 projects, the solution builds. (don't forget using System.Threading; in your App.cs)
这篇关于在 Xamarin.Forms 中使用 Thread.Sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!