Open In App

Main Thread in C#

Last Updated : 21 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In C#, the Main method is the entry point of any console application. It is the first method that is executed when you run a C# program.

Here’s an example of a simple console application with a Main method:

C#




using System;
 
class Program {
    static void Main() {
        Console.WriteLine("Hello, world!");
    }
}


Output

Hello, world!

In this example, the Main method simply writes the message “Hello, world!” to the console using the Console.WriteLine method.

The Main method has a specific signature that is required by the C# language. It must be a static method that returns void, and it can take an array of strings as its parameter, which is typically used to pass command-line arguments to the application.

Here’s an example of a Main method that takes command-line arguments:

C#




using System;
 
class Program {
    static void Main(string[] args) {
        if (args.Length > 0) {
            Console.WriteLine("The first argument is: {0}", args[0]);
        } else {
            Console.WriteLine("No arguments were passed.");
        }
    }
}


Output

No arguments were passed.

In this example, we check if any command-line arguments were passed to the application, and if so, we print the first argument to the console using string interpolation. If no arguments were passed, we print a message indicating so.

C# provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called an thread, and each thread defines a separate path of execution.

Main Thread

When a C# program starts up, one thread begins running immediately. This is usually called the main thread of our program. Properties:

  • It is the thread under which other “child” threads will be created.
  • Often, it must be the last thread to finish execution because it performs various shutdown actions.

Example: 

CSharp




// C# program to illustrate the working
//  of main thread and child thread
using System;
using System.Threading;
 
public class GFG {
 
    // Main thread
    static public void Main()
    {
        Console.WriteLine("Welcome to the Main thread");
 
        // Child threads
        Thread thrA = new Thread(childthread);
        Thread thrB = new Thread(childthread);
        thrA.Start();
        thrB.Start();
    }
 
    public static void childthread()
    {
        Console.WriteLine("Welcome to the Child thread");
    }
}


Output:

Welcome to the Main thread
Welcome to the Child thread
Welcome to the Child thread

Explanation: The above program consists of only one thread that is known as the main thread. The main thread works just like other thread but it starts automatically, you need not to require any Start() method to start the execution of the main thread. Both thrA and thrB are the child thread of main thread. First main thread starts its working after that child thread starts their working.

How to access Main thread?

For accessing main thread you require the Thread class object to refer it. You can create this by using the CurrentThread property of the Thread class. It will return the reference to the thread in which it used. So when you use CurrentThread property inside the main thread you will get the reference of the main thread. After that, you will get control over the main thread just like another thread. Example: 

CSharp




// C# program to illustrate
// how to access main thread
using System;
using System.Threading;
 
public class GFG {
 
    // Main Method
    static public void Main()
    {
        Thread thr;
 
        // Get the reference of main Thread
        // Using CurrentThread property
        thr = Thread.CurrentThread;
 
        // Display the name of
        // the main Thread
        if (thr.Name == null) {
 
            Console.WriteLine("Main thread does not have name");
        }
 
        else {
 
            Console.WriteLine("The name of main "+
                      "thread is: {0}", thr.Name);
        }
 
        Console.WriteLine();
 
        // Display the priority of main thread
        Console.WriteLine("The priority of main"+
                " thread is: {0}", thr.Priority);
 
        // Set the name of main thread
        thr.Name = "Main Thread";
        Console.WriteLine();
 
        // Display the name of main thread
        Console.WriteLine("The name of main "+
                  "thread is: {0}", thr.Name);
    }
}


Output:

Main thread does not have name

The priority of main thread is: Normal

The name of main thread is: Main Thread
Deadlocking by using Main Thread

We can create a deadlock by just using Main thread, i.e. by just using a single thread. The following C# program demonstrates this. Example: 

CSharp




// C# program to demonstrate deadlock
// using the Main thread
using System;
using System.Threading;
 
public class GFG {
 
    // Main Method
    public static void Main()
    {
 
        try {
 
            Console.WriteLine("Enter into DEADLOCK!!");
 
            Thread.CurrentThread.Join();
 
            // the following statement
            // will never execute
            Console.WriteLine("This statement will never execute");
        }
 
        catch (ThreadInterruptedException e) {
            e.ToString();
        }
    }
}


Output:

Enter into DEADLOCK!!

Runtime Error:

Max real time limit exceeded due to either by heavy load on server or by using sleep function

Explanation: The statement “Thread.currentThread().join()”, will tell the Main thread to wait for this thread(i.e. wait for itself) to die. Thus the Main thread waits for itself to die, which is nothing but a deadlock.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads