简体   繁体   中英

async method callback with Task.ContinueWIth?

I have a method that pulls some HTML via the HttpClient like so:

public static HttpClient web = new HttpClient();
public static async Task<string> GetHTMLDataAsync(string url)
{                    
    string responseBodyAsText = "";
    try
    {
       HttpResponseMessage response = await web.GetAsync(url);
       response.EnsureSuccessStatusCode();
       responseBodyAsText = await response.Content.ReadAsStringAsync();
    }
    catch (Exception e)
    {
       // Error handling
    }

    return responseBodyAsText;
}

I have another method that looks like so:

private void HtmlReadComplete(string data)
{
    // do something with the data
}

I would like to be able to call GetHTMLDataAsync and then have it call HtmlReadComplete on the UI thread when the html has been read. I naively thought this could somehow be done with something that looks like

GetHTMLDataAsync(url).ContinueWith(HtmlReadComplete);

But, I can't get the syntax correct, nor am I even sure that's the appropriate way to handle it.

Thanks in advance!

public async void ProcessHTMLData(string url)
{
    string HTMLData = await GetHTMLDataAsync(url);
    HTMLReadComplete(HTMLData);
}

or even

public async void ProcessHTMLData(string url)
{
    HTMLReadComplete(await GetHTMLDataAsync(url));
}

You're close, but ContinueWith() takes a delegate with Task as its parameter, so you can do:

GetHTMLDataAsync(url).ContinueWith(t => HtmlReadComplete(t.Result));

Normally, you should be careful with using Result together with async , because Result blocks if the Task hasn't finished yet. But in this case, you know for sure that the Task is complete, you Result won't block.

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