Xamarin 应用程序在循环时显示空白页

Xamarin app shows blank page while looping

我正在 Xamarin 上制作一个 Android 应用程序,我希望这段代码一遍又一遍地循环。 但是当它循环播放时,它几乎什么都没有显示

public MainPage()
{
    InitializeComponent();
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(2000);
        string app = "notepad";
        HttpClient httpClient = new HttpClient();
        var result = httpClient.GetAsync("LINK/ob/ob.php?text=" + app).Result;
        var contents = result.Content.ReadAsStringAsync().Result;

        string decider = contents.ToString();
        if (decider.Length > 7)
        {
            van.Text = "The " + app + " is ON";
            van.TextColor = Xamarin.Forms.Color.Green;
        }
        else
        {
            van.Text = "The " + app + " is off";
        }
    }

}

首先,不要在构造函数中执行此操作。这样做可以保证您的页面在代码完成之前不会显示

第二,不要在 Thread.Sleep() 的循环中执行此操作,而是使用计时器

Timer timer;
int counter;

protected override void OnAppearing()
{
    timer = new Timer(2000);
    timer.Elapsed += OnTimerElapsed;
    timer.Enabled = true;
}

private void OnTimerElapsed(object sender, ElapsedEventArgs a)
{
  counter++;
  if (counter > 100) timer.Stop();

  // put your http request code here

  // only the UI code updates should run on the main thread
  MainThread.BeginInvokeOnMainThread(() =>
  {
    if (decider.Length > 7)
    {
        van.Text = "The " + app + " is ON";
        van.TextColor = Xamarin.Forms.Color.Green;
    }
    else
    {
        van.Text = "The " + app + " is off";
    }
  });
}