-1

I'm trying to write a C# console application that uses HttpClient to scrape web pages. When FunctionOne is called, what's the best way to ensure that "A" is written to the console before "B"? Whenever I run my code, "B" is always written before "A". Thanks in advance for the help!

public class MyClass
{
    public void FunctionOne(string url)
    {   
        FunctionTwoAsync(url);

        Console.WriteLine("B");
    }

    private async void FunctionTwoAsync(string url)
    {
        var httpClient = new HttpClient();
        var htmlContent = await httpClient.GetStringAsync(url);
        var htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(htmlContent);

        Console.WriteLine("A");
    }
}
Tony
  • 3
  • 1
  • 4
    Watch out for async void https://stackoverflow.com/questions/12144077/async-await-when-to-return-a-task-vs-void – Linus Nov 12 '20 at 22:18

3 Answers3

2

Your FunctionTwoAsync method is an async method, it means this method works Asynchronous.

When you need the result of methode or need this method completes, you must be use await keyword for async method

So, Change your code like this:

public class MyClass {

public async Task FunctionOne(string url)
{   
    await FunctionTwoAsync(url);

    Console.WriteLine("B");
}

private async Task FunctionTwoAsync(string url)
{
    var httpClient = new HttpClient();
    var htmlContent = await httpClient.GetStringAsync(url);
    var htmlDocument = new HtmlDocument();
    htmlDocument.LoadHtml(htmlContent);

    Console.WriteLine("A");
}
}
Mofid.Moghimi
  • 907
  • 1
  • 6
  • 13
  • This explains nothing. It would be a better answer if you explain what the problem is and why this code works – TheGeneral Nov 13 '20 at 00:22
  • This worked, thanks @Mofid.Moghimi! I paired your sample solution with the [link](https://stackoverflow.com/questions/12144077/async-await-when-to-return-a-task-vs-void) that @Linus provided above to get clarity on the 'what' and 'why'. Thanks again! – Tony Nov 13 '20 at 19:26
0

To make A before B, you neeb to await FunctionTwoAsync and make FunctionOne an async function

 public async void FunctionOne(string url)
 {   
    await FunctionTwoAsync(url);

    Console.WriteLine("B");
 }
urchmaney
  • 618
  • 5
  • 7
0

You should make the FunctionOne also async and wait for the execution of the second function:

public class MyClass
{
    public async Task FunctionOne(string url)
    {   
        await FunctionTwoAsync(url);

        Console.WriteLine("B");
    }

    private async Task FunctionTwoAsync(string url)
    {
        var httpClient = new HttpClient();
        var htmlContent = await httpClient.GetStringAsync(url);
        var htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(htmlContent);

        Console.WriteLine("A");
    }
}