C# – Multithreading

The Main Thread

using System;
using System.Threading;

namespace MultithreadingApplication {
   class MainThreadProgram {
      static void Main(string[] args) {
         Thread th = Thread.CurrentThread;
         th.Name = "MainThread";
         
         Console.WriteLine("This is {0}", th.Name);
         Console.ReadKey();
      }
   }
}
Sr.No.Property & Description
1CurrentContext Gets the current context in which the thread is executing.
2CurrentCulture Gets or sets the culture for the current thread.
3CurrentPrinciple Gets or sets the thread’s current principal (for role-based security).
4CurrentThread Gets the currently running thread.
5CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run-time.
6ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread.
7IsAlive Gets a value indicating the execution status of the current thread.
8IsBackground Gets or sets a value indicating whether or not a thread is a background thread.
9IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool.
10ManagedThreadId Gets a unique identifier for the current managed thread.
11Name Gets or sets the name of the thread.
12Priority Gets or sets a value indicating the scheduling priority of a thread.
13ThreadState Gets a value containing the states of the current thread.

Creating Threads

using System;
using System.Threading;

namespace MultithreadingApplication {
   class ThreadCreationProgram {
      public static void CallToChildThread() {
         Console.WriteLine("Child thread starts");
      }
      static void Main(string[] args) {
         ThreadStart childref = new ThreadStart(CallToChildThread);
         Console.WriteLine("In Main: Creating the Child thread");
         Thread childThread = new Thread(childref);
         childThread.Start();
         childThread.Join(1000);
         Console.ReadKey();
      }
   

Thread Pool

List<string> urls = new(){
    "https://www.google.com/",
    "https://www.duckduckgo.com/",
    "https://www.yahoo.com/",
};

foreach (var url in urls)
{
    ThreadPool.QueueUserWorkItem((state) => CheckHttpStatus(url));
}

async and await

static void Main()
    {
        Task task = new Task(CallMethod);
        task.Start();
        task.Wait();
        Console.ReadLine();
    }

    static async void CallMethod()
    {
        string filePath = "E:\\sampleFile.txt";
        Task<int> task = ReadFile(filePath);

        Console.WriteLine(" Other Work 1");
        Console.WriteLine(" Other Work 2");
        Console.WriteLine(" Other Work 3");

        int length = await task;
        Console.WriteLine(" Total length: " + length);

        Console.WriteLine(" After work 1");
        Console.WriteLine(" After work 2");
    }

    static async Task<int> ReadFile(string file)
    {
        int length = 0;

        Console.WriteLine(" File reading is stating");
        using (StreamReader reader = new StreamReader(file))
        {
            // Reads all characters from the current position to the end of the stream asynchronously
            // and returns them as one string.
            string s = await reader.ReadToEndAsync();

            length = s.Length;
        }
        Console.WriteLine(" File reading is completed");
        return length;
    }
static async Task Main(string[] args)
   {
     await callMethod();
     Console.ReadKey();
   }

   public static async Task callMethod()
   {
     Method2();
     var count = await Method1();
     Method3(count);
   }

   public static async Task<int> Method1()
   {
     int count = 0;
     await Task.Run(() =>
     {
       for (int i = 0; i < 100; i++)
       {
         Console.WriteLine(" Method 1");
         count += 1;
       }
     });
     return count;
   }

   public static void Method2()
   {
     for (int i = 0; i < 25; i++)
     {
       Console.WriteLine(" Method 2");
     }
   }

   public static void Method3(int count)
   {
     Console.WriteLine("Total count is " + count);
   }