Creating a simple thread

To create a thread, we simple call one argument constructor of Thread class and pass as argument the function, we want to execute as thread.

In below example, the function MyThread() is passed to the Thread class constructor and it executes as a thread:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadPrograms
{
    class Program
    {
        static void Main(string[] args)
        {

            var t1 = new Thread(MyThread);
            t1.Start();
            Console.WriteLine("This is main thread");
        }

        static void MyThread()
        {
            Console.WriteLine("Running in a thread");
        }
    }
}

 

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *