background preloader

Threading

Facebook Twitter

C# Tutorial - Using The ThreadPool. A thread pool takes away all the need to manage your threads - all you have to do is essentially say "hey!

C# Tutorial - Using The ThreadPool

Someone should go do this work! ", and a thread in the process' thread pool will pick up the task and go execute it. And that is all there is to it. Granted, you still have to keep threads from stepping on each other's toes, and you probably care about when these 'work items' are completed - but it is at least a really easy way to queue up a work item. In fact, working with the ThreadPool is so easy, I'm going to throw all the code at you at once. We have three arrays at the top of the program: one for input to the work items (inputArray), one for the results (resultArray), and one for the ManualResetEvents (resetEvents). So we initialize these arrays, and then we get to a for loop, which is where we will be pushing out these work items. So what are we queuing here?

So what are we doing in this DoWork function? Pretty simple, eh? That's it for this intro to thread pools in C#. Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on. Threading in C# - Free E-book. Threading in C# Joseph Albahari Last updated: 2011-4-27 Translations: Chinese | Czech | Persian | Russian | Japanese Download PDF Part 1: Getting Started C# supports parallel execution of code through multithreading.

Threading in C# - Free E-book

A C# client program (Console, WPF, or Windows Forms) starts in a single thread created automatically by the CLR and operating system (the “main” thread), and is made multithreaded by creating additional threads. All examples assume the following namespaces are imported: using System; using System.Threading; class ThreadTest{ static void Main() { Thread t = new Thread (WriteY); t.Start(); for (int i = 0; i < 1000; i++) Console.Write ("x"); } static void WriteY() { for (int i = 0; i < 1000; i++) Console.Write ("y"); }} The main thread creates a new thread t on which it runs a method that repeatedly prints the character “y”.

Once started, a thread’s IsAlive property returns true, until the point where the thread ends. Done static void Go(){ if (! Done Done (usually!) Join and Sleep. Threading in C# - Part 4 - Advanced Topics. Threading in C# Joseph Albahari Last updated: 2011-4-27 Translations: Chinese | Czech | Persian | Russian | Japanese Download PDF Part 4: Advanced Threading Earlier, we said that the need for synchronization arises even in the simple case of assigning or incrementing a field.