Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# Joining Threads
Next article icon

C# Main Thread

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, threads are the smallest units of execution that allow parallel execution of code, enabling multiple tasks to run concurrently within a single process. The Thread class in the System.Threading namespace is used to create and manage threads. In C#, the Main method is the entry point of any console application. It is the first method that is executed when we run a C# program.

Example 1: Demonstration of a Single-Threaded Console Application with a Main Method.

C#
// C# program to demonstrate the basic usage  // of Main method in a single-threaded application using System;  class Geeks {     // Main Thread     static void Main()     {         Console.WriteLine("Hello, Geek");     } } 

Output
Hello, Geek 

Explanation: In the above example, the Main method simply writes the message “Hello, Geek” 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.

Example 2: Main Method That Takes Command-Line Arguments

C#
// C# program to demonstrate the  // Main method with command-line arguments using System;  class Geeks { 	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:

If no arguments are passed:

No arguments were passed.

Main Thread

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

Properties of the Main Thread:

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


Example: Main Thread and Child Threads

C#
// C# program to illustrate the  // main thread and child threads using System; using System.Threading;  public class Geeks {     // 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 demonstrates how the main thread creates two child threads. The main thread starts running immediately when the program begins, printing “Welcome to the Main thread.” Then, it creates two child threads (thrA and thrB) which print “Welcome to the Child thread.” These child threads run concurrently after being started by the Start() method.

Accessing the Main Thread

To access the main thread, you can use the Thread.CurrentThread property. This property returns a reference to the current thread. By using it inside the main thread, you can get a reference to the main thread itself. 

Example: Demonstration of How to access the main thread in C#

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

Output
Main thread does not have a name  The priority of the main thread is: Normal  The name of the main thread is: Main Thread 

Explanation: This example demonstrates how to access the main thread using Thread.CurrentThread. It checks whether the main thread has a name (by default, it does not), displays the priority of the main thread, sets the name of the main thread, and then displays the new name.

Deadlocking Using the Main Thread

A deadlock occurs when a thread is waiting on itself to finish, causing the program to hang. This can be demonstrated using Thread.CurrentThread.Join(), which tells the main thread to wait for itself to complete, resulting in a deadlock.

Example:

C#
// C# program to demonstrate a  // deadlock using the Main thread using System; using System.Threading;  public class Geeks { 	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:

DeadLockCSharp

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.



Next Article
C# Joining Threads
author
ankita_saini
Improve
Article Tags :
  • C#
  • CSharp Multithreading

Similar Reads

  • C# Thread Class
    In C#, multi-threading is implemented using the Thread class, which is part of the System.Threading namespace. This class allows for the creation, management, and control of threads within an application. The Thread class provides various methods and properties to handle thread execution, prioritize
    7 min read
  • C# Joining Threads
    In C#, multiple threads can be created and run concurrently to perform parallel tasks. Sometimes it is necessary to wait for one thread to finish its execution before proceeding or for all threads to complete before continuing further. The Thread.Join() method allows one thread to wait for another t
    5 min read
  • C# Multithreading
    C# is a multi-paradigm programming language that supports several programming styles, including procedural, object-oriented, and functional programming. One of the essential features of C# is its support for multithreading, which enables developers to write applications that can perform multiple tas
    10 min read
  • How to Create Threads in C#?
    Multithreading enables concurrent task execution in C#. It improves performance and responsiveness. We can create threads using the System.Threading namespace. With the help of Threads, we can achieve multitasking and can define their behavior using different methods provided by the Thread Class. Ex
    6 min read
  • C# Types of Threads
    Multithreading is one of the core features in C# that allows multiple tasks to be performed concurrently. Threads allow your application to run multiple tasks simultaneously, improving performance, and resource utilization. In C#, there are two types of threads. Foreground ThreadsBackground ThreadsN
    4 min read
  • How to Terminate a Thread in C#?
    In C#, threads are used to achieve tasks concurrently, a fundamental feature in multithreading and parallel programming. However, there are scenarios where we need to terminate a thread. There are different ways to terminate a thread and in this article, we will discuss those ways with their code im
    6 min read
  • C# Thread Priority in Multithreading
    In a multithreaded environment, each thread has a priority that determines how frequently the thread is allocated CPU resources by the operating system. The Thread.Priority property in C# is used to set or get the priority of a thread. A programmer can explicitly assign a priority to a thread using
    3 min read
  • How to Thread Lock Work in C#?
    C# makes the concurrent execution of a code possible with the help of threads. The namespace System. Threading which is pre-built in C# supports the use of threads. Typically we create threads for the concurrent execution of a program. But in certain cases we may not want our program to be run concu
    4 min read
  • Thread.CurrentThread Property in C#
    A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as CurrentThread to check the current running thread. Or in other words, the value of this property indicates the current running thread. Syntax: public static Thread CurrentThr
    2 min read
  • C# | Thread(ThreadStart) Constructor
    Thread(ThreadStart) Constructor is used to initialize a new instance of a Thread class. This constructor will give ArgumentNullException if the value of the parameter is null. Syntax: public Thread(ThreadStart start); Here, ThreadStart is a delegate which represents a method to be invoked when this
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences