简体   繁体   中英

C# HttpClient Async-Await - Unable to Guarantee 'A' Before 'B'

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");
    }
}

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");
}
}

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");
 }

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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM