Reputation: 3
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
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
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