deepak
deepak

Reputation: 121

How to spawn thread in C#

Could anyone please give a sample or any link that describes how to spawn thread where each will do different work at the same time.

Suppose I have job1 and job2. I want to run both the jobs simultaneously. I need those jobs to get executed in parallel. how can I do that?

Upvotes: 11

Views: 21303

Answers (3)

user3114005
user3114005

Reputation: 31

Threads in C# are modelled by Thread Class. When a process starts (you run a program) you get a single thread (also known as the main thread) to run your application code. To explicitly start another thread (other than your application main thread) you have to create an instance of thread class and call its start method to run the thread using C#, Let's see an example

  using System;
  using System.Diagnostics;
  using System.Threading;

  public class Example
  {
     public static void Main()
     {
           //initialize a thread class object 
           //And pass your custom method name to the constructor parameter

           Thread thread = new Thread(SomeMethod);

           //start running your thread

           thread.Start();

           Console.WriteLine("Press Enter to terminate!");
           Console.ReadLine();
     }

     private static void SomeMethod()
     {
           //your code here that you want to run parallel
           //most of the cases it will be a CPU bound operation

           Console.WriteLine("Hello World!");
     }
  }

You can learn more in this tutorial Multithreading in C#, Here you will learn how to take advantage of Thread class and Task Parallel Library provided by C# and .NET Framework to create robust applications that are responsive, parallel and meet the user expectations.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500835

Well, fundamentally it's as simple as:

ThreadStart work = NameOfMethodToCall;
Thread thread = new Thread(work);
thread.Start();
...

private void NameOfMethodToCall()
{
    // This will be executed on another thread
}

However, there are other options such as the thread pool or (in .NET 4) using Parallel Extensions.

I have a threading tutorial which is rather old, and Joe Alabahari has one too.

Upvotes: 22

Mahesh Velaga
Mahesh Velaga

Reputation: 21971

Threading Tutorial from MSDN!

http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx

Upvotes: 1

Related Questions