0

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!

4

1 回答 1

3

That's exactly what your code does.

Calling GetStringAsync() will kick off an asynchronous request.

When you await the first one, your method will stop executing until that one finishes; the other request will still be executing during that time.

Had you awaited the first task before kicking off the second task, it would not have done what you want.

于 2013-09-02T16:02:47.537 回答