-1

I have a task who want to call from the constructor class but it's really slow for executing. Is there a way to force this task?

private async Task GetExchange()
{
    NewsStack.IsVisible = false;
    SearchStack.IsVisible = false;
    ExchangeStack.IsVisible = true;
    try
    {
        var client = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri("https://coinlore-cryptocurrency.p.rapidapi.com/api/tickers/?start=0&limit=100"),
            Headers =
            {
                { "x-rapidapi-host", "coinlore-cryptocurrency.p.rapidapi.com" },
                { "x-rapidapi-key", "yourAPIkey" },
            },
        };
        using (var response = await client.SendAsync(request))
        {
            var exchange = new Exchange();
            response.EnsureSuccessStatusCode();
            var body = await response.Content.ReadAsStringAsync();
            var exchangeBody = JsonConvert.DeserializeObject<Exchange>(body);
           
            exchange = exchangeBody;

            this.exchangeBodyList = new List<SearchCrypto>();

            foreach (var item in exchange.CryptoExchange)
            {
                this.exchangeBodyList.Add(new SearchCrypto()
                {
                    Name = item.Name,
                    Symbol = item.Symbol
                });
            }

            this.exchangeTest = exchange;
            
            lstExchange.ItemsSource = exchangeBody.CryptoExchange;
        }

        dateTimeRefresh.Text = "Last Update: " + DateTime.Now.ToString("HH:mm:ss");
    }
    catch (Exception ex)
    {
        await DisplayAlert("Alert", "Please, check your internet connection.", "OK");
    }
}

I call this task in constructor like that:

Task.Run(() => this.GetExchange()).Wait();

I'm not sure if there's a way to force it in another way.

Also I accepting tips or examples for code optimization.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Ben Johnson
  • 753
  • 1
  • 9
  • 18
  • 3
    Strong heed, if those are real API credentials get new ones now. You never want to post this information. – Trevor Dec 21 '21 at 18:56
  • I update the question. – Ben Johnson Dec 21 '21 at 19:00
  • 1
    @BenJohnson, it's still in the publicly viewable edit history, so you'll still need to get new creds. – computercarguy Dec 21 '21 at 19:03
  • 1
    Force what? Why is it slow? Is it your server? The internet connection? The processing time on the client? You can't fix "slow" unless you know which specific part of the process is slow. Also, calling async code from the constructor is not a good idea. There are multiple alternate ways you can do it - for example, using an `async OnAppearing` call in the page. – Jason Dec 21 '21 at 19:12
  • Related: [Can constructors be async?](https://stackoverflow.com/questions/8145479/can-constructors-be-async) and [Call asynchronous method in constructor?](https://stackoverflow.com/questions/23048285/call-asynchronous-method-in-constructor) – Theodor Zoulias Dec 23 '21 at 02:51

2 Answers2

2

In general, asynchronous work is a poor fit for constructors. Ideally, constructors should be short and fast and do almost nothing - setting some member variables, perhaps doing some argument validation, that's about it.

Instead of trying to cram I/O into a constructor, consider using a factory pattern. So you create a factory, which can then create an instance of the type you want using an asynchronous method like async Task<MyType> CreateAsync(). CreateAsync can then call GetExchange naturally (i.e., asynchronously) and pass exchangeBodyList and exchangeTest into the constructor.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
0

What point are you trying to accomplish by forcing the API call to finish? Just like most things, the server will give a response when it's performed all it's operations, not before. The only way to force the result early is to close the connection and not wait for an answer. If you just want it to speed up and finish quicker, then you'll need to speed up the server side code and any DB calls.

Just like in any program, there's no way to force code to run faster. You can't make the computer run faster. You can force it to run a thread at a higher priority, but I'm pretty sure that's not going to make much speed difference and it's probably not the format you need the code to run in.

Speeding up code isn't really on topic here, unless you have an actual, specific error or issue you want to fix, but a general "speed up my code" doesn't work here. It might be on topic on Code Review, maybe, but not here.

computercarguy
  • 2,173
  • 1
  • 13
  • 27