我想运行类似于以下代码的代码块。该代码的目的是在不阻塞 UI 线程的情况下以一秒为周期发出 HTTP 请求。
private void GetCodeFromTheServer()
{
WebClient client = new WebClient();
string code = client.DownloadString(new Uri(@"http://example.com/code"));
Toast.MakeText(this, "Code: " + code, ToastLength.Long).Show();
}
最佳答案
如果您需要每隔 1 秒执行一次操作,您可以使用计时器。我自己在 Xamarin.Android 中使用过这样的代码:
private void CountDown ()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
}
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
}
OnTimedEvent 将每秒触发一次,您可以在异步任务中进行调用。
关于c# - 如何创建一个在后台运行的计时器而不用 Xamarin 阻塞 UI 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27196590/