Can one process run multiple threads in C#

Answer: Yes, in a single process we execute multiple threads in C# multithreading program. For example in below program, main () is a process that can create multiple child threads. We have created and run two threads t1 and t2.

 

using System;
using System.Threading;
class ThreadDemo
{
    private static Object _lock = new Object();

    //Main process, also is a thread
    static void Main(string[] args)
    {
        //Main process can Create multiple threads
        // and execute them.

        //Create multiple child threads
        Thread t1 = new Thread(threadFunc);
        Thread t2 = new Thread(threadFunc);

        //Start child threads
        t1.Start();
        t2.Start();
    }

    //Function that thread will call
    static void threadFunc()
    {
        String arr = "Interview Sansar !!!";
        lock (_lock)
        {

            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i]);
            }
        }

    }
}


 

NOTES: This is very basic and simple C# multithreading interview question that is generally asked to a fresher.

Tips: While answering this type of simple question, try to answer your more knowledge yourself without further question on threading. For example, you can answer as  lock can be used in threadFunc()stated above to show synchronization and lock knowledge.

You can follow other C# interview question – need of synchronization in C# multi-threading .

 



Leave a Comment