简体   繁体   中英

List from async Task in sync MainPage

I'm really looking for the solution and can't find proper instruction. I have async method in RestService.cs

 public async static Task<List<Convert>> CheckBTCUSDAsync()
        {
            HttpClient client = new HttpClient();
            string restUrl = 
    "https://bitbay.net/API/Public/BTCUSD/trades.json";
            HttpResponseMessage responseGet = await 
    client.GetAsync(restUrl);
            if (responseGet.IsSuccessStatusCode)
            {
                var response = await responseGet.Content.ReadAsStringAsync();
                List<Convert> currencies = Convert.FromJson(response);
                //Debug.WriteLine(currencies[0].Date);
                return currencies;
            }
            else
            {
                //Debug.WriteLine("***************");
                //Debug.WriteLine("*****FALSE*****");
                //Debug.WriteLine("***************");
                return null;
            }
        }

I want to use it in my MainPage but of course I cant use await in sync method. I found that some devs suggest putting async tasks in eg OnStart method: https://xamarinhelp.com/xamarin-forms-async-task-startup/ I need to to Bind the returned list to picker in Xaml but of course when trying to use:

var convert = RestService.CheckBTCUSDAsync().Result;

It hangs the UI thread. Anyone knows what is the best/easiest way to resolve this?

这就是我在应用程序上运行它的方式

var convert = Task.Run(() => RestService.CheckBTCUSDAsync()).Result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM