user13877792
user13877792

Reputation: 3

Make WebClient().DownloadString async

How i can make this code non-blocking async so it doesn't block the UI? do i need to use another library ?

public static double GetRsi(string symbol1, string interval1, string period1)
            {
                //API KEY FROM alphavantage.co
                string API_KEY = "xxxxxxx";
                
                StringBuilder urlBuilder = new StringBuilder();
                urlBuilder.Append($"https://www.alphavantage.co/");
                urlBuilder.Append($"query?function=RSI&symbol={symbol1}&interval={interval1}&time_period={period1}&series_type=open&apikey={API_KEY}");
                string jsonData = new WebClient().DownloadString(urlBuilder.ToString());
    
    
                var machine = JsonConvert.DeserializeObject<AlphavantageData>(jsonData);
                var _RSI = machine.TechnicalAnalysisRsi.Last().Value.Rsi;
                return _RSI; 
            }

Upvotes: 0

Views: 457

Answers (2)

Maxim Kosov
Maxim Kosov

Reputation: 1980

You can use DownloadStringTaskAsync as was already suggested. I also wanted to mention that using WebClient is not recommended in the modern C#/.NET code. Try System.Net.Http.HttpClient instead. It's lighter and is async from the get go.

Please, check out msdn.

Example:

// You need 1 client per application
static readonly HttpClient client = new HttpClient();

...
var url = $"https://www.alphavantage.co/query?function=RSI&symbol={symbol1}&interval={interval1}&time_period={period1}&series_type=open&apikey={API_KEY}";
var response = await client.GetStringAsync(url);

Upvotes: 2

Sean
Sean

Reputation: 62532

WebClient has a DownloadStringTaskAsync that you can use:

public static async Task<double> GetRsi(string symbol1, string interval1, string period1)
{
    //API KEY FROM alphavantage.co
    string API_KEY = "xxxxxxx";
    
    StringBuilder urlBuilder = new StringBuilder();
    urlBuilder.Append($"https://www.alphavantage.co/");
    urlBuilder.Append($"query?function=RSI&symbol={symbol1}&interval={interval1}&time_period={period1}&series_type=open&apikey={API_KEY}");
    
    using(var webClient = new WebClient())
    {
        string jsonData = await webClient.DownloadStringTaskAsync(urlBuilder.ToString());

        var machine = JsonConvert.DeserializeObject<AlphavantageData>(jsonData);
        var _RSI = machine.TechnicalAnalysisRsi.Last().Value.Rsi;
        return _RSI; 
    }
}

Upvotes: 2

Related Questions