Pregunta

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;
¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top