Creating Threads

A client program (Console, WPF, or Windows Forms) starts in a single thread that’s created automatically by the CLR and operating system (the “main” thread). Here it lives out its life as a single-threaded application, unless you do otherwise, by creating more threads (directly or indirectly).
You can create and start a new thread by instantiating a Thread object and calling its Start method. The simplest constructor for Thread takes a ThreadStart delegate: a parameterless method indicating where execution should begin. Consider the following example.


using System;
using System.Threading;
namespace ConsoleApplication1
    class Program
        static void Main()
            Thread t = new Thread(WriteY); // Kick off a new thread
            t.Start(); // running WriteY()
            // Simultaneously, do something on the main thread.
            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”. Simultaneously, the main thread repeatedly prints the character “x” On a single-core computer, the operating system must allocate “slices” of time to each thread (typically 20 ms in Windows) to simulate concurrency, resulting in repeated blocks of “x” and “y”. On a multicore or multiprocessor machine, the two threads can genuinely execute in parallel (subject to competition by other active processes on the computer), although you still get repeated blocks of “x” and “y” because of subtleties in the mechanism by which Console handles concurrent requests.
A thread is said to be preempted at the points where its execution is interspersed with the execution of code on another thread. The term often crops up in explaining why something has gone wrong!


You may also like...