Search code examples
c#stringparallel-processingparallel.foreach

How to add strings without any problems using parallel foreach?


Here is my current code:

Parallel.ForEach(Arguments, Argument =>
{
    if (Argument != Command_Name)
    {
        WebRequest web_request = WebRequest.Create("https://www.aol.com/?command=1&domain=" + Argument);
        web_request.Timeout = 5000;
        ((HttpWebRequest)web_request).UserAgent = "Mozilla Firefox 5.0";
        HttpWebResponse web_response = (HttpWebResponse)web_request.GetResponse();
        StreamReader response = new StreamReader(web_response.GetResponseStream(), Encoding.UTF8);
        Message += Argument + " => " + response.ReadToEnd() + Environment.NewLine;
    }
});

This code does not work correctly, I am looking for a SMALL alternative that does. This code returns some of the arguments in the Message string... What is a good way to multi-threaded string addition? That is what I need.

More info: The Message string will return a, b, and c sometimes while others it will only return just a or b...

I appreciate any help on this, thanks!


Solution

  • You can use a thread-safe collection to store the messages such as ConcurrentBag<T>.Then just make the concetanation after the loop:

    var messages = new ConcurrentBag<string>();
    Parallel.ForEach(Arguments, Argument =>
    {
       ... 
       messages.Add(Argument + " => " + response.ReadToEnd());
    }
    var result = string.Join(Environment.NewLine, messages);