通过计时器以Xamarin形式重复异步任务

esh*_*any 5 c# asynchronous timer xamarin.forms

我是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;
        });

    }
Run Code Online (Sandbox Code Playgroud)

在计时器中重新加载内容页面可以解决问题,因此,如果有人可以帮助我,将不胜感激

Mic*_*des 5

您只需要将异步方法调用包装在Task.Run()中,例如:

Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
  Task.Run(async () =>
  {
    var time = await RequestTimeAsync();
    // do something with time...
  });
  return true;
});
Run Code Online (Sandbox Code Playgroud)


esh*_*any -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>();
        }

    }
Run Code Online (Sandbox Code Playgroud)