Creating and Running Threads

This section provides a tutorial example on how to create and run a thread that executes a static method.

There are 4 basic steps to create and run a thread:

1. Create a "public static void" method as the execution method to hold the code that you want to execute in the thread. For example:

   public static void HelloMethod() {...}

2. Create a System.Threading.ThreadStart delegate to represent the execution method: For example:

   using System.Threading;
   ThreadStart myDelegate = new ThreadStart(HelloMethod);

3. Create a System.Threading.Thread object with the delegate: For example:

   using System.Threading;
   Thread myThread = new Thread(myDelegate);

4. Run the thread by calling the Start() method on the thread object. For example:

   myThread.start();

This is a tutorial example on how to create and run a thread:

// HelloThread.cs
// Copyright (c) 2015, HerongYang.com, All Rights Reserved.

using System.Threading;
public class HelloThread {
   public static void Main() {
      ThreadStart myDelegate = new ThreadStart(HelloMethod);
      Thread myThread = new Thread(myDelegate);
      myThread.Start();
      System.Console.WriteLine("Hello from a main program");
   }
   public static void HelloMethod() {
      System.Console.WriteLine("Hello from a sub thread");
   }
}

When executed, I got this output:

Hello from a main program
Hello from a sub thread

Cool. I know how to create and run a thread now.

Last update: 2015.

Table of Contents

 About This Book

 Introduction of C# (C Sharp)

 Data Type and Variables

 Logical Expressions and Conditional Statements

 Arrays and Loop Statements

 Data Type Features

 Floating-Point Data Types

 Passing Parameters to Methods

 Execution Environment Class

 Visual C# 2010 Express Edition

 Class Features

 C# Compiler and Intermediate Language

 Compiling C# Source Code Files

 MSBuild - Microsoft Build Engine

 Memory Usages of Processes

Multithreading in C#

 What Is Multithreading?

 System.Threading.Thread Class

Creating and Running Threads

 Threads to Run Instance Methods

 Performance Impact with Multiple Threads

 Multi-Thread Programs on Multi-CPU Systems

 Maximum Number of Threads in a Program

 Async Feature from C# 5

 System.IO.FileInfo Class

 System.Diagnostics.FileVersionInfo Class

 WPF - Windows Presentation Foundation

 Partial Classes and Partial Methods

 Outdated Tutorials

 References

 PDF Printing Version