The Parallel ForEach feature of .Net 4.0 makes threading even easier. There is no reason to not try to take advantage of today’s multi-core hardware. Thread synchronization aside, here’s a very simple sample:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ThreadingSamples { class Program { static void Main(string[] args) { List<int> numbers = new List<int>(); for (int i = 0; i < 100; i++) numbers.Add(i); Parallel.ForEach(numbers, number => { Console.WriteLine(number); } ); } } }
Horrible example... Thread contention for the console makes this useless.
ReplyDeletehttp://msdn.microsoft.com/en-us/library/dd460720.aspx
Taught me what I expected.
DeleteThe content of the parallel work is not the focus of this example, but the setup is.
ReplyDeletemay be you should set background-attachment property set to fixed. this will help with not losing focus while reading.
ReplyDeleteSome more sample
ReplyDeletepublic void Main()
{
dynamic blogs = new List {
"http://remondo.net",
"http://www.nikhilk.net",
"http://blogs.teamb.com/craigstuntz",
"http://mehmetcatkin.com/",
"http://blogs.msdn.com/b/lukeh"
};
Parallel.ForEach(blogs, blog => ProcessBlogs(blog));
Console.ReadLine();
}
private void ProcessBlogs(string blog)
{
dynamic client = new WebClient();
string reply = client.DownloadString(blog);
Console.WriteLine("Thread: {0} - {1} - Size {2}", Thread.CurrentThread.ManagedThreadId, blog, reply.Length);
Console.WriteLine(reply);
}
Some more sample
ReplyDeletepublic void Main()
{
dynamic blogs = new List {
"http://remondo.net",
"http://www.nikhilk.net",
"http://blogs.teamb.com/craigstuntz",
"http://mehmetcatkin.com/",
"http://blogs.msdn.com/b/lukeh"
};
Parallel.ForEach(blogs, blog => ProcessBlogs(blog));
Console.ReadLine();
}
private void ProcessBlogs(string blog)
{
dynamic client = new WebClient();
string reply = client.DownloadString(blog);
Console.WriteLine("Thread: {0} - {1} - Size {2}", Thread.CurrentThread.ManagedThreadId, blog, reply.Length);
Console.WriteLine(reply);
}