I'm just trying to understand how does processing in parallel work in c#. This is my code example:
Parallel.For(0, 1000, index =>
{
try
{
var url = "some exemplary url";
HttpStatusCode statusCode;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
StringBuilder data = new StringBuilder();
using (HttpWebResponse myWebResponse = (HttpWebResponse)request.GetResponse())
{
statusCode = myWebResponse.StatusCode;
if (myWebResponse.GetResponseStream() != null)
{
StreamReader streamReader = new StreamReader(myWebResponse.GetResponseStream());
using (streamReader)
{
string line = string.Empty;
while ((line = streamReader.ReadLine()) != null)
{
data.Append(line);
}
}
}
MailMessage msg = new MailMessage();
msg.Subject = "subject";
msg.From = new MailAddress("no-reply@domain.co.uk");
msg.To.Add("name.name@domain.com");
msg.Body = data.ToString();
msg.IsBodyHtml = true;
var newSmtp = new SmtpClient();
newSmtp.Send(msg);
Interlocked.Increment(ref count);
}
}
catch (Exception e)
{
}
});
Technicalities of the code are not that important here since it works fine. However, a request to "some exemplary URL" is fairly time-consuming and after processing +-30 requests I'm getting "Operation has timed out" exception thrown. When I change the Parallel for loop and add MaxDegreeOfParallelism option like so
Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 4 }, index =>
{
I no longer get the exception thrown. So, I'm trying to figure out why adding this option fixed the workflow? Looks to me that it's something to do with thread management? My understanding of it is that when I do not specify the number of threads, new ones are created before waiting for the previous one to finish? Am I right, or is it something wrong with my code?