C# Tutorials - Herong's Tutorial Examples - v3.32, by Herong Yang
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) 2010 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.
Table of Contents
Logical Expressions and Conditional Statements
Visual C# 2010 Express Edition
C# Compiler and Intermediate Language
Compiling C# Source Code Files
MSBuild - Microsoft Build Engine
Threads to Run Instance Methods
Performance Impact with Multiple Threads
Multi-Thread Programs on Multi-CPU Systems
Maximum Number of Threads in a Program
System.Diagnostics.FileVersionInfo Class
WPF - Windows Presentation Foundation