I'm new to await async, I want to make sense of what I studied about the subject in this real scenario:
I have a simple code that reads bitcoin price which takes 1-2 seconds, I don't want to lock the UI using await async and still give a status if it is loading or done:
private void button_Click(object sender, RoutedEventArgs e)
{
Task<int> bitcoinPriceTask = GetBitcoinPrice();
lblStatus.Content = "Loading...";
}
protected async Task<int> GetBitcoinPrice()
{
IPriceRetrieve bitcoin = new BitcoinPrice();
string price = bitcoin.GetStringPrice();
txtResult.Text = price;
lblStatus.Content = "Done";
return 1;
}
as requested, here is the implementation of BitcoinPrice class:
public class BitcoinPrice : IPriceRetrieve
{
public BitcoinPrice()
{
Url = "https://www.google.com/search?q=bitcoin%20price";
}
public string Url { get; }
public string GetStringPrice()
{
var html = RetrieveContent();
html = MetadataUtil.GetFromTags(html, "1 Bitcoin = ", " US dollars");
return html;
}
public float GetPrice()
{
throw new NotImplementedException();
}
public string RetrieveContent()
{
var request = WebRequest.Create(Url);
var response = request.GetResponse();
var dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
var responseFromServer = reader.ReadToEnd();
return responseFromServer;
}
}