Making threads in C# is basically making different paths for a process to run. By threading, we make multiple instances of the same process or simply we can say multiple copies of the same process. Each Thread runs independently but threads can share resources with each other. The resources which the Threads share are:
Create Thread Methods
You can simply create two or more methods which you want to run parallel in threads. So here in the example below, there are two public methods named as Thread1 and Thread2.
To explain threading let us consider the following example:
- Create a new Project.
- Add a new class ThreadProgram.
- Include threading library by.
Now after that type the following code:
public void Thread1()
for (int i = 0; i < 1000; i++)
Console.WriteLine("thread 1 :"+i);
//The above mentioned code will execute for 1000 time.
public void Thread2()
for (int i = 1000; i < 2000; i++)
Console.WriteLine("thread 2 :" + i);
//The above mentioned code will execute paralell 2000times with thread 1.
} //end method
} //end class
Creating Threads in C# and Running Thread Methods
Thread class provides the facility to run two or more methods at the same time. So for the methods Thread1 and Thread2 use instance/object of Thread class and pass the method as an object in the parameters of the constructor.
So add another class with the name of Program. In this class you will execute class ThreadProgram in the following way:
ThreadProgram thread = new ThreadProgram();
// (ThreadProgram) is basically the class which we are using and (thread) is an instance of (ThreadProgram).
Thread thread1 = new Thread(thread.Thread1);
// (Thread) is basically the instance of type thread related to ThreadProgram class which we are using and(thread1) is a thread of this instance.
Thread thread2 = new Thread(thread.Thread2);
// thread1 is started. Start() is a built in function in C# associated with thread which starts a thread.