I’m coding an app for Windows 8 which needs to get the HTML of a particular site. It was working well when i coded it into the button event which is in the MainPage. However, when I tried to do it in my class ‘Band’:
public Band(String Name)
{
this.Name = Name;
GetHtmlDocument();
GenerateId();
GetAlbumDocument();
GenerateLogo();
GeneratePhoto();
CreateAlbumList();
}
private async void GetHtmlDocument()
{
HttpClientHandler handler = new HttpClientHandler();
HttpClient client = new HttpClient(handler as HttpMessageHandler) { BaseAddress = new Uri(@"http://www.metal-archives.com/bands/" + Name) };
var r = await client.GetAsync(client.BaseAddress);
string html = null;
if (r.IsSuccessStatusCode) html = await r.Content.ReadAsStringAsync();
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(html);
DocumentBand = document;
}
It came to
var r = await client.GetAsync(client.BaseAddress);
line and then proceed from the GenerateId() method as it is in the constructor. But in order to process GenerateId() method, GetHtmlDocument() method must be finished. What should i do in this situation?
My main language is Java and I’m very new to the C#, so there may huge coding or naming mistakes.
I would do something like this:
From your code, you would have to call init separately:
The reason for having a separate
Init()function is becauseasyncandawaitcannot be used inside of the constructor.