James Ezechukwu
James Ezechukwu

Reputation: 617

How to collect the returned value of an awaited method in a variable in another method

So I am trying to grab the source code from a url and here is my code:

public async Task<string> grabPageHtml(Uri pageUrl)
{
    var request = WebRequest.Create(pageUrl) as HttpWebRequest;
    request.Method = "GET";
    WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(
                                        request.BeginGetResponse,
                                        request.EndGetResponse, request);

    var responseStream = responseObject.GetResponseStream();

    var sr = new StreamReader(responseStream);
    received = sr.ReadToEndAsync().Result;      
    return received;
} 

The code works correctly and returns the sourcecode. The problem is assigning "received" to a string variable in another method.

Tried this:

string pageHtml = grabPageHtml(pageUrl)

but pageHtml outputs System.Threading.Tasks.Task'1[System.String] to the console instead of the source code.

Upvotes: 0

Views: 145

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

pageHtml outputs System.Threading.Tasks.Task1[System.String]` to the console instead of the source code.

That's because your method returns a Task<string>, not a string. You need to extract that string result somehow. It should be:

public async Task FooAsync()
{
    string pageHtml = await GrabPageHtmlAsync(pageUrl);
    Console.WriteLine(pageHtml);
}

As a side note, don't block on async code. Using Task.Result may lead to deadlocks. Also, using HttpClient would make your code a bit cleaner, removing the need to call FromAsync:

public Task<string> GrabPageHtmlAsync(Uri pageUrl)
{
    var httpClient = new HttpClient();
    return httpClient.GetStringAsync(pageUrl);
} 

Upvotes: 3

Related Questions