我是xamarin.forms开发的新手,我仍然可以从网上找到的几个教程中迈出第一步。 我有一个异步任务,从date.jsontest.com返回时间 我有一个计时器,减少标签中的文本。 我想把异步任务放在计时器中,以便它重复自己并在标签上显示时间但是我得到的不能将异步lamba转换为func
这里我的代码请帮帮我,谢谢
static async Task<string> RequestTimeAsync()
{
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync("http://date.jsontest.com/");
var jsonObject = JObject.Parse(jsonString);
return jsonObject["time"].Value<string>();
}
}
protected override async void OnAppearing()
{
base.OnAppearing();
timeLabel.Text = await RequestTimeAsync();
Device.StartTimer(TimeSpan.FromSeconds(1), () => { // i want the taks to be put
//here so that it gets repeated
var number = float.Parse(button.Text) - 1;
button.Text = number.ToString();
return number > 0;
});
}
重新加载定时器中的内容页面可以解决问题,所以如果有人可以帮助我,我们将不胜感激
答案 0 :(得分:4)
您只需要在Task.Run()中包装异步方法调用,例如:
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
Task.Run(async () =>
{
var time = await RequestTimeAsync();
// do something with time...
});
return true;
});
答案 1 :(得分:-1)
解决
就像那个一样简单
private async void ContinuousWebRequest()
{
while (_keepPolling)
{
timeLabel.Text = "call: "+counter+" "+ await RequestTimeAsync()+Environment.NewLine;
// Update the UI (because of async/await magic, this is still in the UI thread!)
if (_keepPolling)
{
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
}
static async Task<string> RequestTimeAsync()
{
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync("http://date.jsontest.com/");
var jsonObject = JObject.Parse(jsonString);
TimePage.counter++;
return jsonObject["time"].Value<string>();
}
}
答案 2 :(得分:-1)
或者你可以试试这个:
static async Task<string> RequestTimeAsync()
{
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync("http://date.jsontest.com/");
var jsonObject = JObject.Parse(jsonString);
return jsonObject["time"].Value<string>();
}
}
protected override async void OnAppearing()
{
base.OnAppearing();
var Text = await RequestTimeAsync();
Device.StartTimer(TimeSpan.FromSeconds(1), () => {
// i want the taks to be put
//here so that it gets repeated
var jsonDateTsk = RequestTimeAsync();
jsonDateTsk.Wait();
var jsonTime = jsonDateTsk.Result;
var number = float.Parse(Text) - 1;
var btnText = $"{number}";
return number > 0;
});
}
答案 3 :(得分:-1)
一个简单的时钟演示一秒计时器动作:
Device.StartTimer(TimeSpan.FromSeconds(1), doitt);
bool doitt()
{
label1.Text = DateTime.Now.ToString("h:mm:ss");
return true;
}