简体   繁体   中英

Xamarin app shows blank page while looping

I'm making an Android application on Xamarin and I want this code to be looped over and over. But when it's looping it shows literally nothing

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";
        }
    }

}

first, don't do this in the constructor. Doing so guarantees that your page won't display until the code completes

second, instead of doing this in a loop with Thread.Sleep() use a timer instead

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";
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM