Tutorialspoint.dev

How to schedule a thread for execution in C#

Thread.Start Method is responsible for a thread to be scheduled for execution. This method can be overloaded by passing different parameters to it.

  • Start()
  • Start(Object)

Start()

This method tells the operating system to change the state of the current instance to Running. Or in other words, due to this method the thread start its execution.

Syntax:

public void Start ();

Exceptions:

  • ThreadStateException : If the thread has already been started.
  • OutOfMemoryException : If there is not enough memory available to start a thread.

Example:



// C# program to illustrate the
// use of Start() method
using System;
using System.Threading;
  
class GThread {
  
    // Non-static method
    public void Job()
    {
        for (int X = 0; X < 4; X++) {
            Console.WriteLine(X);
        }
    }
}
  
// Driver Class
public class GFG {
  
    // Main Method
    public static void Main()
    {
        // Creating object of GThread class
        GThread obj = new GThread();
  
        // Creating and initializing a thread
        Thread thr = new Thread(new ThreadStart(obj.Job));
  
        // Start the execution of Thread
        // Using Start() method
        thr.Start();
    }
}

Output:

0
1
2
3

Start(Object)

This method tells the operating system to change the state of the current instance to Running. It passes an object containing data to be used by the method the thread executes. This parameter is optional.

Syntax:

public void Start (object parameter);

Here, parameter is an object that contains data to be used by the method the thread executes.

Exceptions:

  • ThreadStateException : If the thread has already been started.
  • OutOfMemoryException : If there is not enough memory available to start a thread.
  • InvalidOperationException : If the thread was created using a ThreadStart delegate instead of a ParameterizedThreadStart delegate.

Example:

// C# program to illustrate the
// use of Start(Object) method
using System;
using System.Threading;
  
// Driver Class
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Creating object of GFG class
        GFG obj = new GFG();
  
        // Creating and initializing threads
        Thread thr1 = new Thread(obj.Job1);
        Thread thr2 = new Thread(Job2);
  
        // Start the execution of Thread
        // Using Start(Object) method
        thr1.Start(01);
        thr2.Start("Hello")
    }
  
    // Non-static method
    public void Job1(object value)
    {
        Console.WriteLine("Data of Thread 1 is: {0}", value);
    }
  
    // Static method
    public static void Job2(object value)
    {
        Console.WriteLine("Data of Thread 2 is: {0}", value);
    }
}

Output:

Data of Thread 1 is: 1
Data of Thread 2 is: Hello

Reference:



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter