2016-03-03 45 views
11

使用了Thread.Sleep我想執行以下在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,但我仍然得到

名稱「主題」不存在的當前上下文。

This site建議Thread.Sleep可用於Xamarin.Forms。我在一個共享的項目中,而不是PCL。

+1

'Thread.Sleep'應同時使用幾乎所有的UI框架來避免(的WinForms/WPF/Xamarin.Forms/Silverlight的/ ... ),因爲它會凍結UI線程並掛起UI。 –

+0

它僅用於演示目的,但謝謝您的補充。 – testing

回答

23

如果你想等待

異步:await Task.Delay(10000);

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

但請儘量避免阻塞UI線程確保良好的用戶體驗並保持您的應用程序不變sponsive。

在Xamarin.Forms

使用了Thread.Sleep有兩種Xamarin.Forms模板:

  • Xamarin.Forms便攜式類庫

    由於PCL子集機制,你沒有機會得到Thread.Sleep

    更新2017: PCL現在已被棄用。如果使用.net標準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)

+0

你是對的,UI線程不應該被阻止。這裏僅用於演示目的。 – testing

+0

你知道爲什麼'Thread'沒有被識別嗎?在鏈接的頁面上,它似乎能以某種方式起作用。 – testing

+1

因爲Core庫的PCL配置文件不同,我認爲你沒有'Thread.Sleep'。您在PCL中選擇的支持的平臺越多,可以使用的支持的類別/功能越少。 –

3

你可以嘗試使用

await Task.Delay(milliseconds); 

,如果你想要把一個延遲你的線程。

阻止,你可以做

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

你可以這樣做,但這與我想嘗試的例子不同。該線程應該被第一個按鈕不被延遲阻塞。你知道我錯過了什麼嗎?子項目中的參考? – testing

+0

@testing: - 更新了我的答案以阻止它。請檢查 –