0

My method returns a StringBuilder and passes in a List<string> of urls. I believe the parent will wait until the child has completed.

BUT it seems like this method is exiting before it is done because the caller has a Messagebox pop-up and my Debug.WriteLine(count); is still counting in the debug window.

My main issue is:
the result StringBuilder object doesn't have as much appended to it as it should after looping. Could it be possible that StringBuilder is getting reset by using a Task?

int count = 1;

StringBuilder result = new StringBuilder();

var parent = Task.Factory.StartNew(() =>
{
    foreach (string url in pURI)
    {
        try
        {
            var child = Task.Factory.StartNew(() =>
            {
                using (HttpClient client = new HttpClient())
                {
                    result.Append(client.GetStringAsync(url).Result.ToLower());
                    Debug.WriteLine(count);
                    count++;
                }
            }, TaskCreationOptions.AttachedToParent);
        }
        catch (Exception cancelException)
        {
            MessageBox.Show(cancelException.Message);
        }

        Debug.WriteLine(url.ToString());
    }
});

parent.Wait();

return result;
Fedor
  • 1,548
  • 3
  • 28
  • 38
Mike
  • 71
  • 7

1 Answers1

0

Inside the loop, GetStringAsync to a string var local to that bit of code. When you have the string, lock the StringBuilder while you do the append.

Untested example, cos I'm not doing it all for you. :)

 using (HttpClient client = new HttpClient())
 {
     string s = client.GetStringAsync(url).Result.ToLower();
     lock(result)
     {
         result.Append(s);
     }

     Debug.WriteLine(count);
     count++;
 }

For more info, see here.

Craig Graham
  • 1,161
  • 11
  • 35
  • Please give an example on how to lock using my code as an example – Mike Jan 28 '14 at 07:02
  • I decided to go another route. I will post my solution. – Mike Jan 28 '14 at 18:05
  • After checking that you added .Result, that is what worked for me too. I will still give you the solution since we were on the same page. Thank you. – Mike Jan 28 '14 at 18:10