C# 如何创建在后台运行的计时器而不使用Xamarin阻塞UI线程?
我想运行一段类似于以下代码的代码。代码的目的是在1秒的时间内发出HTTP请求,而不阻塞UI线程C# 如何创建在后台运行的计时器而不使用Xamarin阻塞UI线程?,c#,android,multithreading,xamarin,C#,Android,Multithreading,Xamarin,我想运行一段类似于以下代码的代码。代码的目的是在1秒的时间内发出HTTP请求,而不阻塞UI线程 private void GetCodeFromTheServer() { WebClient client = new WebClient(); string code = client.DownloadString(new Uri(@"http://example.com/code")); Toast.MakeText(
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();
}
您将无法在活动主线程上调用web。使用异步任务执行代码。异步任务将在后台运行,下载内容时将为您显示Toast。下面的示例将有所帮助
private class GetStringTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String str = "...";
/** String From Web **/
return str;
}
@Override
protected void onPostExecute(String address) {
// Show Toast Here
}
}
私有类GetStringTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串str=“…”;
/**来自Web的字符串**/
返回str;
}
@凌驾
受保护的void onPostExecute(字符串地址){
//在这里敬酒
}
}
如果你需要每隔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将每秒触发一次,您可以在异步任务中执行调用 如果要修改“OnTimedEvent”上的任何视图属性,应使用“RunOnUiThread(()=>somethingonthythuithread)”;如果要一次性事件,只需设置timer.AutoReset=false;