Ich erstelle eine Android-Anwendung auf Xamarin und möchte, dass dieser Code immer wieder wiederholt wird. Aber wenn es sich wiederholt, zeigt es buchstäblich nichts
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";
}
}
}
🤔 А знаете ли вы, что...
C# был представлен в 2000 году и стал частью платформы .NET Framework.
Erstens tun Sie dies nicht im Konstruktor. Dadurch wird garantiert, dass Ihre Seite erst angezeigt wird, wenn der Code vollständig ist
Zweitens, anstatt dies in einer Schleife mit Thread.Sleep()
zu tun, verwenden Sie stattdessen einen Timer
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";
}
});
}