C# Tutorials - Herong's Tutorial Examples - v3.32, by Herong Yang
Threads to Run Instance Methods
This section provides a tutorial example on how to use a thread to run instance method.
.NET also allows you to run instance methods in threads as shown in the tutorial example:
// TimerThread.cs
// Copyright (c) 2010 HerongYang.com. All Rights Reserved.
using System.Threading;
public class TimerThread {
public static void Main() {
Timer hisTimer = new Timer("His Timer", 10);
Thread hisThread = new Thread(hisTimer.Run);
hisThread.Start();
Timer herTimer = new Timer("Her Timer", 7);
Thread herThread = new Thread(herTimer.Run);
herThread.Start();
}
}
public class Timer {
private string name;
private int duration;
public Timer(string n, int d) {
name = n;
duration = d;
}
public void Run() {
System.Console.WriteLine("{0}: Starts for {1} seconds...",
name, duration);
Thread.Sleep(duration*1000);
System.Console.WriteLine("{0}: Ding! Ding!", name);
}
}
When executed, I got this output:
His Timer: Starts for 10 seconds... Her Timer: Starts for 7 seconds... Her Timer: Ding! Ding! His Timer: Ding! Ding!
Notice that starting from .NET 2, you can create a Thread object without using a Delegate object explicitly. Just put the method name in the Thread constructor. The compiler will create Delegate object automatically for you.
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