Nobodyelse
Nobodyelse

Reputation: 99

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?

Upvotes: 1

Views: 893

Answers (1)

P.N.
P.N.

Reputation: 645

This is how I got it to work on my app

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

Upvotes: 2

Related Questions