在Xamarin.Forms中使用Thread.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.Threading
和System.Threading.Tasks
,但我仍然得到
当前上下文中不存在名称“Thread”。
该站点表明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个项目,则构建解决方案。 (不要忘记使用System.Threading;在你的App.cs中)
你可以尝试使用
await Task.Delay(milliseconds);
如果你想在你的线程中加一个延迟。
对于阻止你可以做到
Task.Delay(TimeSpan.FromSeconds(5)).Wait();