I am trying get a string from an async method that returns a string as type Task string
My code:
class DataScraper
{
private static readonly HttpClient client = new HttpClient();
public static async Task<string> getParagraph()
{
string subject1 = "";
string subject2 = "";
Dictionary<string, string> parameters = new Dictionary<string, string>()
{
{ "Subject1", subject1 },
{ "Subject2", subject2 }
};
try
{
string result = await PostHTTPRequestAsync("http://watchout4snakes.com/wo4snakes/Random/RandomParagraph", parameters);
return await Task.FromResult(result);
}
catch (Exception ex)
{
return ex.Message;
}
}
private static async Task<string> PostHTTPRequestAsync(string url, Dictionary<string, string> data)
{
using (HttpContent formContent = new FormUrlEncodedContent(data))
using (HttpResponseMessage response = await client.PostAsync(url, formContent).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}
When using it in another class like this:
string s = DataScraper.getParagraph();
I get an error that says:
Cannot implicitly convert type 'System.Threading.Tasks.Task<string>' to 'string'
return await Task.FromResult(result);and just doreturn result;string s = await DataScraper.getParagraph(). And yes, that means that the method that code runs from should also be marked as async, and the method that calls that should be marked as async, all the way up the call stack until you get to the main method or an event handler.await: ` string s = await DataScraper.getParagraph();`Asyncto your async methods. So, it should begetParagraphAsync(). That way the caller doesn't have to think about it, he/she will know it's async immediatly.