Creating and Running Threads in C#: Executing Static and Non-Static Methods Concurrently
Learn how to implement multithreading in C# to execute code concurrently. This tutorial demonstrates creating and starting threads for both static and non-static methods, explaining the `ThreadStart` delegate and highlighting the importance of thread management for improving application performance.
Creating and Running Threads in C#: Static and Non-Static Methods
This article demonstrates how to create and start threads in C# to execute both static and non-static methods concurrently. Multithreading allows you to perform tasks simultaneously, potentially improving application performance.
Starting Threads with Static Methods
To start a thread that runs a static method, you don't need to create an instance of the class. You pass the method's name directly to the `ThreadStart` delegate when creating the `Thread` object.
Thread myThread = new Thread(new ThreadStart(MyClass.MyStaticMethod));
myThread.Start();
Example:
using System;
using System.Threading;
public class MyClass {
public static void MyStaticMethod() {
// ... code to run in the new thread ...
}
}
// ... (Main method to create and start the threads) ...
The output order is unpredictable because the operating system's scheduler determines when each thread runs.
Starting Threads with Non-Static Methods
To run a non-static method, you first need to create an instance of the class. You then pass a method group (a reference to the method on the object instance) to the `ThreadStart` delegate.
MyClass myObject = new MyClass();
Thread myThread = new Thread(new ThreadStart(myObject.MyInstanceMethod));
myThread.Start();
Example:
using System;
using System.Threading;
public class MyClass {
public void MyInstanceMethod() {
// ... code to run in the new thread ...
}
}
// ... (Main method to create and start the threads) ...
Again, the output order is unpredictable due to context switching.
Example: Different Tasks on Different Threads
This example shows how to run different methods concurrently on separate threads:
using System;
using System.Threading;
public class MyClass {
public static void Task1() { Console.WriteLine("Task 1"); }
public static void Task2() { Console.WriteLine("Task 2"); }
}
// ... (Main method to create and start threads for Task1 and Task2) ...