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()
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:
using System;
using System.Threading;
class GThread {
public void Job()
{
for ( int X = 0; X < 4; X++) {
Console.WriteLine(X);
}
}
}
public class GFG {
public static void Main()
{
GThread obj = new GThread();
Thread thr = new Thread( new ThreadStart(obj.Job));
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:
using System;
using System.Threading;
class GFG {
public static void Main()
{
GFG obj = new GFG();
Thread thr1 = new Thread(obj.Job1);
Thread thr2 = new Thread(Job2);
thr1.Start(01);
thr2.Start( "Hello" )
}
public void Job1( object value)
{
Console.WriteLine( "Data of Thread 1 is: {0}" , value);
}
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:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...