I have an email that uses web requests to get the different parts(text, html and subject). I want the program to get them at the same time to reduce time. I have written a simplified version below of what I am trying to achieve.
public static async Task<MailMessage> GetEmailMessage(string subjectUrl, string bodyUrl)
{
var mailMessage = new MailMessage();
var subjectTask = new HttpClient().GetStringAsync(subjectUrl);
var bodyTask = new HttpClient().GetStringAsync(bodyUrl);
mailMessage.Subject = await subjectTask;
mailMessage.Body = await bodyTask;
return mailMessage;
}
I would like the program to for the subject and the body and once it has both, return the MailMessage.
I am new to this async, any help would be appreciated.
========= SOLUTION =========
So thanks to @SLaks for making me realise the problem wasn't in my function. It was in the way I was calling it. Turns out, in my case (I think cause I am returning a reference type not a value type), I had to call the Task<>.Result before it would actually do the waiting.
ie: This will NOT wait for completion:
var mailMessage = GetEmailMessage("urlhere", "http://www.google.com");
But this will (Notice the "Result" being called for:
var mailMessage = GetEmailMessage("urlhere", "http://www.google.com").Result;
I hope this post helps someone else with the same problem. Happy coding!