Parallel Processing


Published on

Using the Task Parallel Library in .NET, compared to Threads

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

Parallel Processing

  2. 2. ABOUT ME
  3. 3. MANYCORE SHIFTDespite Moore’s Law, manufacturers have hit a practical limitfor single core processors • Smaller transistors are more prone to “leak” • Faster clock speeds require more power, which produces more heatInstead of making one strong processor, make smallerparallel processors
  4. 4. INTRODUCING PARALLELEXTENSIONSaka Task Parallel Library (TPL)First CTP’d November 30th, 2007Added to .NET 4.0Easy way to take advantage of multi-core parallel processingin applications while abstracting out thread management andscheduling
  5. 5. THREADSThread t = new Thread(ThreadStart)Common Scenarios: • Long running queries against a data layer • Disk / Network IO • Separate blocking operations from the UI threadHiding latency, adding perceived performanceNo actual performance gainNo automatic management of thread execution • Leading to context switching, invalidating cache, extra memory usage
  6. 6. THREADPOOLThreadPool.QueueUserWorkItem(Action)Automatically takes advantage of multi core processors viaThreadPool schedulingUses a delegateRuns with a Global and Local QueueDoesn’t offer any handles into the thread • Fire and forget
  8. 8. BACKGROUND WORKERBasically a wrapper for ThreadPoolProvides hooks to report progress(ProgressChanged), report completion(RunWorkerCompleted), and supports cancellation(CancellationPending)Could do all the same stuff with a ThreadPool, but this wiresit up for you
  9. 9. TASKSTask t = new Task(Action)Similar to ThreadPool – uses a delegate, queue’dBut provides hooks into and across tasks:t.Wait() / Task.WaitAll(t, t2, …) – allows main thread to wait fortask completiont.ContinueWith(new Task()) – specifies a task should startafter another task completest.Cancel() – cancel any running taskt = new Task<int>() – return an int value from the task to theexecuting thread
  10. 10. SYSTEM.THREADING.TASKS.PARALLELParallel.ForEach(collection, Action)Static methods for executing parallel tasksParallel.ForEach executes each loop as a TaskJust like multi-threading, keep in mind race conditions,concurrency issues, shared state, etc.Parallel.For(intTo, intFrom, Action)Parallel.Invoke(Action, …, Action)
  11. 11. PLINQCollection.AsParallel()LINQ version of Parallel ExtensionsParallelQuery and ParallelEnumerableCollection.AsParallel().Where(x => x.IsPrime())Can specify cancellation conditions, degree ofparallelism, buffering options
  12. 12. OLD STUFFAsync, Await keywords in .NET 5.0 (VB and C#)string DownloadJson(string url){ Console.WriteLine(“Fetching JSON”); WebClient client = new WebClient(); client.DownloadStringCompleted += (result) => { Console.WriteLine(“JSON: “ + result); return result; } client.DownloadStringAsync(url);}
  13. 13. NEW STUFFasync Task<string> DownloadJson(string url){ Console.WriteLine(“Fetching JSON”); WebClient client = new WebClient(); string json = await client.DownloadStringTaskAsync(url); Console.WriteLine(“JSON: “ + json); return json;}
  14. 14. NEW STUFF, TRANSLATEDTask<string> DownloadJson(string url){ Console.WriteLine(“Fetching JSON”); WebClient client = new WebClient(); Task<string> t = client.DownloadStringTaskAsync(url); t.Start(); t.Wait(); string json = t.Value; Console.WriteLine(“JSON: “ + json); return json;}
  15. 15. NEW STUFF, FLOWCHARTEDMain Thread DownloadJson(url) delegate(result) OnCompleted Call DownloadJson await WebClient.DownloadStringTaskAsync
  16. 16. MORE NEW STUFFDataFlowUses “blocks” to perform operationsvar ab = ActionBlock<int>((i) => { Console.WriteLine(i.ToString(“c”); });ab.Post(4);var tb = TransformBlock<int, int>((i) => { return i * 3; });tb.LinkTo(ab);tb.Post(6);