Threads in C#

 

Introduction:

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:

  1. Variables
  2. Memory
  3. Disk
  4. File
  5. Network

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:

  1. Create a new Project.
  2. Add a new class ThreadProgram.
  3. Include threading library by.

Now after that type the following code:

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: