Csharp parallel (#2443)

* [csharp/en] - Attempts to address issue #1064 by using a different parallel example.
This commit is contained in:
chriszimmerman 2016-10-11 03:33:17 -04:00 committed by ven
parent c8fa53ca1f
commit 7b96973204

View File

@ -547,28 +547,22 @@ on a new line! ""Wow!"", the masses cried";
// PARALLEL FRAMEWORK // PARALLEL FRAMEWORK
// http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
var websites = new string[] {
"http://www.google.com", "http://www.reddit.com",
"http://www.shaunmccarthy.com"
};
var responses = new Dictionary<string, string>();
// Will spin up separate threads for each request, and join on them var words = new List<string> {"dog", "cat", "horse", "pony"};
// before going to the next step!
Parallel.ForEach(websites, Parallel.ForEach(words,
new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads new ParallelOptions() { MaxDegreeOfParallelism = 4 },
website => word =>
{
// Do something that takes a long time on the file
using (var r = WebRequest.Create(new Uri(website)).GetResponse())
{ {
responses[website] = r.ContentType; Console.WriteLine(word);
} }
}); );
// This won't happen till after all requests have been completed //Running this will produce different outputs
foreach (var key in responses.Keys) //since each thread finishes at different times.
Console.WriteLine("{0}:{1}", key, responses[key]); //Some example outputs are:
//cat dog horse pony
//dog horse pony cat
// DYNAMIC OBJECTS (great for working with other languages) // DYNAMIC OBJECTS (great for working with other languages)
dynamic student = new ExpandoObject(); dynamic student = new ExpandoObject();