Threads and the Threadpool

This small demonstration code snippet will show you how to:

  • Create threads to run code in the background of your application
  • Demonstrate how to pass one or more parameters to a background thread
  • Demonstrate how to wait for all background activity to finish before exiting the main program.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
  
namespace ConsoleApplicationThreadTest
{
  
    /// <summary>
    /// This is a simple demonstration of starting background tasks for processing and passing
    /// parameters to them.
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
  
            Console.WriteLine("main thread start");
  
            // we need a tasklist to check when the main thread can safely exit
            var oTasklist = new List<Task>();
  
            // Create 10 tasks. You will find from the console output that the task factory
            // makes its own decissions about the order in which the tasks are started, meaning
            // you can make no assumptions about the order in which they will execute.
            for (int i = 1; i < 11; i++)
            {
                int taskno = i;
                var oTask = Task.Factory.StartNew(() => StaticThreadWorker(taskno));
                oTasklist.Add(oTask);
            }
  
            // Wait for all factory tasks to finish
            Task.WaitAll(oTasklist.ToArray());
  
            // End programm
            Console.WriteLine("main thread end");
        }
  
  
        // A simple background task that waits for a random time of 0-1000ms
        private static void StaticThreadWorker(int t)
        {
            Console.WriteLine("thread start " + t.ToString());
            var random = new Random(t);
            int wait = random.Next(1000);
            Thread.Sleep(wait);
            Console.WriteLine("thread " + t + " ended after " + wait + "ms.");
        }
  
  
    }
}