We have the option to invoke both static and non-static methods during thread execution. When invoking these methods, it is necessary to specify the method name within the ThreadStart class constructor. Static methods can be accessed without instantiating the class; they can be referenced directly by the class name.
using System;
using System.Threading;
public class MyThread
{
public static void Thread1()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
public class ThreadExample
{
public static void Main()
{
Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));
Thread t2 = new Thread(new ThreadStart(MyThread.Thread1));
t1.Start();
t2.Start();
}
}
Output:
The result of the aforementioned program can vary due to the context switching that occurs between the threads.
0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
6
7
8
9
C# Threading Example: non-static method
When dealing with a non-static method, it is necessary to instantiate the class in order to reference it within the constructor of the ThreadStart class.
using System;
using System.Threading;
public class MyThread
{
public void Thread1()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
public class ThreadExample
{
public static void Main()
{
MyThread mt = new MyThread();
Thread t1 = new Thread(new ThreadStart(mt.Thread1));
Thread t2 = new Thread(new ThreadStart(mt.Thread1));
t1.Start();
t2.Start();
}
}
Output:
Similar to the program mentioned earlier, the output of this particular program may vary due to context switching between threads.
0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
6
7
8
9
C# Threading Example: performing different tasks on each thread
Let's consider an instance where we are running distinct techniques on individual threads.
using System;
using System.Threading;
public class MyThread
{
public static void Thread1()
{
Console.WriteLine("task one");
}
public static void Thread2()
{
Console.WriteLine("task two");
}
}
public class ThreadExample
{
public static void Main()
{
Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));
Thread t2 = new Thread(new ThreadStart(MyThread.Thread2));
t1.Start();
t2.Start();
}
}
Output:
task one
task two