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) 2015, 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.

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